Pages

Exception Handling in Java

Exception are errors occurred during run time and which can be traced and handled. If an exception is occurred then our program unexpectedly close showing some error message and unexpected output. Theses errors my occur internally in the program code or through the resources the program is trying to access. The sources of errors may be user-input errors such as giving a wrong value, device errors such as printer not found, physical limitations such as disk full or memory not enough and code errors like array index out of bound. Java provides appropriate mechanism to handle exceptions. The main purpose of handling exception is to inform the user about the error or to take an alternative path to overcome the problem and complete the remaining task.
In Java we handle exception by using try..catch mechanism. Java provides try, catch and finally keywords for handling exception. The program statements that are supposed to generate or produce error and included inside the try block and the statement that handle the error and produce required information are included inside the catch block. The finally block include those statement that has to be executed whether an error occur or not.


Structure of try, catch and finally keyword
try{
    statements that may produce exceptions.
}
catch(ExceptionType ex1){
    statements to handle exception of type ExceptionType
}
finally{
   statements to be executed whether an exception occurs or not.
}

The following program produces divide by zero exception.
ExceptionDemo.java
class ExceptionDemo{
    public static void main(String[] args){
        try{
                int x = 10/0;
                System.out.println(x);
        }
        catch(Exception ex){
            System.out.println("Exception Occured!");
            System.out.println(ex);
       }
   }
}

Output:
Exception Occured!
java.lang.ArthmeticException: / by zero


@msucil

Phasellus facilisis convallis metus, ut imperdiet augue auctor nec. Duis at velit id augue lobortis porta. Sed varius, enim accumsan aliquam tincidunt, tortor urna vulputate quam, eget finibus urna est in augue.

No comments:

Post a Comment