Tuesday, March 27, 2007

Java :: Exceptions :: Nested Exceptions

There is a nice little thing that got introduced in Java 1.4, it's nested exceptions.

Consider the following piece of code:

class LowLevelException extends Exception {
public LowLevelException(String message) {
super(message);
}
}

class HighLevelException extends Exception {
public HighLevelException(String message, Throwable cause) {
super(message, cause);
}
}

public class TryNestedExceptions {
public static void main(String[] args) {
try {
throw new LowLevelException("LowLevelException here.");
} catch(LowLevelException e) {
// While throwing a higher level exception, construct it with
// the LowLevelException as the cause.
try {
throw new HighLevelException("HighLevelException here.", e);
} catch (HighLevelException e1) {
e1.printStackTrace();
}
}
}
}

Let's see the stack trace of the above program:

HighLevelException: HighLevelException here.
at TryNestedExceptions.main(TryNestedExceptions.java:21)
Caused by: LowLevelException: LowLevelException here.
at TryNestedExceptions.main(TryNestedExceptions.java:16)

We also have stack trace of the LowLevelException in the "Caused by:" of HighLevelException's stack trace. This helps us to drill down to the root of the problem. I like the nested exception idea very much. We can nest as many exceptions as we want. For example, if the LowLevelException was caused due to some IOException then while throwing LowLevelException we can nest the IOException.

1 comments:

Simmy said...

thanks, this was handy

Post a Comment