tags:

views:

358

answers:

7

In java there is a possibility of re-throwing the exception but there is any advantage in it?

+4  A: 

Sometimes, you want a specific type of Exception to be thrown by a method, but there are rare instances that cause other Exceptions to be thrown within the method. I often wrap the causal Exception with my desired Exception and then rethrow the desired Exception.

This is really useful when you can't determine that the Exception has caused your operation to fail until control is passed to the calling method (or one of its ancestors), since if the process does eventually fail, I can trace back in the stacktrace to see why.

Steve Moyer
+5  A: 

One example of when you want to rethrow an exception is when you don't really know how to handle it yourself, but you'd like to log that the exception was thrown. Rethrowing it allows you to both capture the stack information that you need to log, and pass the exception up the call stack for the caller to handle.

Bill the Lizard
A: 

I don't think so. If you can't handle it, don't catch it.

duffymo
Except you don't always know what caused the exception, in which case you're not sure whether or not you can handle it until after you did further investigation
Rik
+4  A: 

Sure. If you need to perform some special processing (logging, clean up, etc) for the exception, but can't "handle" it completely, it is common to do the processing and then rethrow the exception. Note, that in many cases (especially cleaning up resources) you probably want a finally clause rather than a catch/rethrow.

Dave Ray
A: 

I haven't done Java in years, but from what I remember it's just like other languages with exceptions and OO. Exceptions can be subclassed, and often, you'll want to catch a base class of many exceptions, but might not be able to handle all of them. So say you're handling a remote file transfer, and want to catch all IOErrors, because you handle most of them, but not DiskFull. You can rethrow that, and let someone else deal with it further up the chain, but deal with the other issues, like TransmissionFailed, by re-doing the transmit.

Lee B
+1  A: 

If you can somehow justify that you need to re-throw the same exception that you caught, I'd argue that there is something wrong with your design.

Catching one exception and re-throwing another makes perfect sense. For instance, you may want to add detailed information that the original exception did not have.

cdonner
+1  A: 
Elijah