Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-throwing exceptions in Java

Tags:

java

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

like image 246
Warrior Avatar asked Dec 03 '22 08:12

Warrior


2 Answers

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.

like image 124
Bill the Lizard Avatar answered Dec 12 '22 04:12

Bill the Lizard


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.

like image 28
Dave Ray Avatar answered Dec 12 '22 03:12

Dave Ray