Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rethrowing exceptions in Java without losing the stack trace

Tags:

java

exception

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

like image 807
ripper234 Avatar asked Jul 08 '09 11:07

ripper234


People also ask

What is Rethrowing exception in Java?

JavaObject Oriented ProgrammingProgramming. Sometimes we may need to rethrow an exception in Java. If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.

What is Rethrowing an exception?

If a catch block cannot handle the particular exception it has caught, you can rethrow the exception. The rethrow expression ( throw without assignment_expression) causes the originally thrown object to be rethrown.

Can we throw and catch the same exception in Java?

The throw keyword in Java is used to explicitly throw either a custom-made exception or in-built exception. But sometimes in the catch block, we need to throw the same exception again. This leads to re-throwing an exception.

How do you throw a caught exception?

The caller has to handle the exception using a try-catch block or propagate the exception. We can throw either checked or unchecked exceptions. The throws keyword allows the compiler to help you write code that handles this type of error, but it does not prevent the abnormal termination of the program.


1 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.

like image 143
Brian Agnew Avatar answered Oct 14 '22 13:10

Brian Agnew