Rethrowing exceptions in Java without losing the stack trace

ripper234 picture ripper234 · Jul 8, 2009 · Viewed 270.1k times · Source

In C#, I can use the throw; statement to rethrow an exception while preserving the stack trace:

try
{
   ...
}
catch (Exception e)
{
   if (e is FooException)
     throw;
}

Is there something like this in Java (that doesn't lose the original stack trace)?

Answer

Brian Agnew picture Brian Agnew · Jul 8, 2009
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.