Rethrowing exceptions in Java without losing the stack trace Rethrowing exceptions in Java without losing the stack trace java java

Rethrowing exceptions in Java without losing the stack trace


catch (WhateverException e) {    throw e;}

will simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.). The exception will maintain the original stack trace.


I would prefer:

try{    ...}catch (FooException fe){   throw fe;}catch (Exception e){    // Note: don't catch all exceptions like this unless you know what you    // are doing.    ...}


You can also wrap the exception in another one AND keep the original stack trace by passing in the Exception as a Throwable as the cause parameter:

try{   ...}catch (Exception e){     throw new YourOwnException(e);}