Home » Java » Rethrowing exceptions in Java without losing the stack trace

Rethrowing exceptions in Java without losing the stack trace

Posted by: admin November 2, 2017 Leave a comment

Questions:

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)?

Answers:
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.

Questions:
Answers:

I would prefer:

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

Questions:
Answers:

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);
}

Questions:
Answers:

In Java is almost the same:

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

Questions:
Answers:

In Java, you just throw the exception you caught, so throw e rather than just throw. Java maintains the stack trace.

Questions:
Answers:

something like this

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

Questions:
Answers:
public int read(byte[] a) throws IOException {
    try {
        return in.read(a);
    } catch (final Throwable t) {
        /* can do something here, like  in=null;  */
        throw t;
    }
}

This is a concrete example where the method throws an IOException. The final means t can only hold an exception thrown from the try block. Additional reading material can be found here and here.