Posted By:
3 Mar, 2014 2:07 pm PST

Exception in JAVA

How to Handle exception in Java?

 

An exception is a unexcepted or error condition.The program you write can generate many type of potential exceptions,such as :

  • You issue a command to read a file from a disk,but the file does not exit there.
  • When user attempt to write data to a disk ,but the disk is full .
  • When program asks for user input,but the user enters invalid data.
  • The program attempts to divide a value by 0 , access an array with a subscript that is too large .

To manage these kinds of error,object-oriented techniques comprise the group of methods known as  expection handling.

When you create a code in which something may go wrong,you place it in try block.A catch block is a segment of code that can handle an exception that might be thrown by try block.

 

Example:

//To show if any error occurs that should be shown on screen

public class ExceptionExample{

               public static void main(String args[]){

                               int num=8,deno=0,div;

                               try{

                                              div = num/deno;

                               }

                               catch(ArithmeticException e){

                                              System.out.println(e.getMessage());

                               }

               }

}

 

Output of the above program is:

/ by zero 

 




Please login to reply to this problem.