views:

95

answers:

2

Hi,

What is the use of rethrowing checked and unchecked exceptions?

+6  A: 

If you want to execute some code when a problem happens without hiding the problem.

For example, let's say you want to rollback changes if an exception occurs while writing to a database:

try {
    writeToDatabase();
} catch(Exception ex) {
    rollbackChanges();
}

If you use this code, the calling function will never find out that an exception occurred.

Instead, you should write

try {
    writeToDatabase();
} catch(Exception ex) {
    rollbackChanges();
    throw ex;
}
SLaks
Why the call to fillInStackTrace? Its documentation does not say what it does when called multiple times, but either it will overwrite the original stack trace, in which case the above code hides the original reason, or then it will do nothing, in which case the above code has unneeded complexity.
Esko Luontola
@esko: You're right; fixed.
SLaks
Don't you usually want to rollback on any exception?
Tom Hawtin - tackline
@Tom: Yes, you probably would.
SLaks
+1  A: 

To be somewhat blunt: to use exception handling.

Consider this, before exceptions (or, before a developer understands how to properly use exception handling) programmers would return error codes like -1 or null if something 'went wrong'. With that in mind, how would you tell something several methods back that it failed (eg: some low level IO method in a large API failed)? You could either string a lot of return nulls/ or -1's together, or just throw an exception so that it migrates back up to somewhere where it should be caught, even the JVM itself if need be as this exception might something you cannot recover from.

So basically, you would rethrow an exception if you are unable to write catch logic that can truly recover from the thrown exception. This is often the case in Java because Java forces you to catch almost all of its Exceptions since most everything is a checked exception.

As for rethrowing checked vs unchecked... Often times I will throw a new unchecked exception (RuntimeExpcetion) from inside a checked exception back up to the container when doing J2EE applications. The container has a default way of handling exceptions and showing the user a default error page. This comes from the Aspect Oriented paradigm. I also wrote about how to do this here.

Zombies