Friday, 5 June 2015

Java Exception Handling Construct

Java exception/error handling is managed via five keywords: try, catch, throw, throws, and finally.

The general form of an exception-handling block is:

try

{

//block of code to be monitored for errors.

}

catch(ExceptionType1 exOb1)

{

//exception handler for ExceptionType1

}

catch(ExceptionType2 exOb2)

{

//exception handler for ExceptionType1

}

.

.

.

finally

{

//block of code to be executed before try block ends

}

The code, which is to be monitored for run-time errors, is put inside a try block. The try block must be enclosed between braces even if there is only one statement in it. There can be zero or more catch statements and zero or one finally statement. Both catch and finally blocks are optional but either one catch block or one finally block is must.

The code in the try block is executed like any other Java code. If the code inside the try block executes successfully then the control goes to finally block if it is present and then the execution continues from the statement just after the end of finally block (i.e. after the end of try statement). If the finally block is not present then the execution continues from the statement just after the last catch block (i.e. after the end of try statement).

If some run-time error occurs while executing the code in try block then JVM throws an Exception/Error. This means an object of type Exception/Error or one of its sub-classes is created depending on the type of the run-time error. This is then compared with the Exception/Error types of the catch blocks in top to bottom order. If a matching catch block is found then the exception/error is handled i.e. program will not terminate. The execution continues with the first statement in the catch block. On completion of the catch block, excution continues with the statement just after the end of try statement. At the most one catch block is executed irrespective of the number of catch blocks. On completion of the catch block, excution continues with the statement just after the end of try statement. At the most one catch block is executed irrespective of the number of catch blocks.

If exception/error does not match with exception/error type of any of the catch blocks, then we say that it is not handled. The execution will immediately return from try block. The code in the finally block will be executed even if the exception/error is not handled. The exception/error will then be handled by outer try block if there is one otherwise it must be handled in the method which called the current method. The exception/error percolates up the hierarchy till it is handled or it is passed to JVM unhandled if not handled even in the main() method which is the first method from which the execution starts. The JVM then simply terminates the program and displays the exception/error details on the monitor/console.



No comments:

Post a Comment