Java

Wednesday, August 10, 2005

Exception Handling

Exceptions in Java extend the Throwable class from the java.lang package. Basically the idea to have exception in a program is to handle the error condition in which we provide a mechanism for separating the error handling routine from the rest of the code and initiate the control flow transfer whenever an error occurs.
Looking at the Throwable class, the hierarchy is explained using the figure below;















In Java, Throwable class is the superclass of all errors and exceptions. Moving ahead with error and exceptions, Error subclass of the Throwble superclass denotes the abnormal condition when a dynamic linking failure or “hard” failure in the Java Virtual Machine occurs.

The Exception class is the superclass of all exceptions. An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exception class doesnot define any method of its own.
Exception handling includes try-catch-finally construct and compile-time checking.

Throw- Throw statement is used to throw exceptions in a program. It means that the particular function is exiting and the control is given to the first catch statement. Any method capable of throwing exception is mentioned in the method signature. Once mentioned in the method signature, a method has no restriction on the number of exceptions that can be thrown.

Finally Clause: Looking at the flow of execution of “try…catch…finally”, we can say that try block is exited via finally. The flow exactly looks like catch…finally…return (to take out of the method). Finally can also be viewed as an acting default catch statement when no catch clause is mentioned.

Propagating Exception: There are certain cases where exceptions can not be handled and in such situation the exception is not handled, it is being propagated to the higher classes and finally if the main class also fails to handle the exception, its upto the Java Virtual Machine to handle the exception.

Runtime Exception: Most of the places we find “RuntimeException Handling – A Controversy”, its because we need to check these during design itself. Basically "Runtime Exception” is not because the system can not handle it or it can not be viewed as system failure but exactly it is because of the program failure as it was required to be checked beforehand.

0 Comments:

Post a Comment

<< Home