Friday, October 5, 2007



What is an Exception Handling?


Exception Handling

What is an Exception ?

Let us see what happens when an exception occurs and is not handled properly

When you compile and run the following program

public class Test{
public static void main(String str[]){
int y = 0;
int x = 1;
// a division by 0 occurs here.
int z = x/y;
System.out.println("after didvision");
}
}

the execution of the Test stops and this is caused by the division by zero at - x/y - an exception has been thrown but has not been handled properly.

How to handle an Exception ?

To handle an Exception, enclose the code that is likely to throw an exception in a try block and follow it immediately by a catch clause as follows

public class Test{
public static void main(String str[]){
int y = 0;
int x = 1;
// try block to "SEE" if an exception occurs
try{
int z = x/y;
System.out.println("after didvision");
// catch clause below handles the
// ArithmeticException generated by
// the division by zero.
} catch (ArithmeticException ae)
{System.out.println(" attempt to divide by 0");}
System.out.println(" after catch ");
}
}

The output of the above program is as follows

attempt to divide by 0
after catch

the statement - System.out.println("after didvision") - is NOT executed, once an exception is thrown, the program control moves out of the try block into the catch block.

No comments: