Monday, June 23, 2008

Overruling uncaught exceptions in Java - how to?

Overruling uncaught exceptions in Java - how to do?

An uncaught exception normally propagates until the default handler (or some other intermediate handler if found on the way) handles it. The default handler prints the detailes message with the exception name and also the stack trace before exiting the process.

Is there a way to nullify the effect of an uncaught exception without handling it? Yes... we can have a finally block with control transfer statements like return or maybe a labelled break. Read more - finally in Java - common uses, ques, etc. >>

Example: overruling an uncaught exception using labelled break in finally

package test;
public class TestFinally {
public static void main(String[] args) {

System.out.println("Inside Try Block");
throw new IOException();
}catch(IOException ioe){
System.out.println("Inside Catch Block");
//... throwing unchecked exceptions - we should not do
throw new RuntimeException();
System.out.println("Inside Finally");
break tryBlock;

System.out.println("Inside main - Outside tryBlock");

Inside Try Block
Inside Catch Block
Inside Finally
Inside main - Outside tryBlock

This approach can be used to nullify an uncaught exception in void methods. For non-void methods, we will similarly follow the other possible approach to nullify an uncaught exception - using a return statement. In this approach we will simply return a default value and the uncaught exception (raised either in the try block or in the catch block while handling the exception raised in the try block) will be overruled.

We can use these two approaches to nullify unchecked exceptions as well (as we can see in the above example where an uncaught RuntimeException in the catch block is also being nullified), but we should avoid doing that as it'll defeat the very purpose of unchecked exception. They are supposed to be program bugs (or design bugs) and they should be treated and not nullified :-)

Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.


No comments: