Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Rethrow" to next catch clause

If there is a try-catch with mutiple catch-blocks, is there way to rethrow an exception to next (not underlaying) catch-clause?

Example:

try {

  // some exception can occur here

} catch (MyException ex) {

  // do something specific

  // rethrow ex to next catch

} catch (Exception ex) {

  // do logging stuff and other things to clean everything up
}

When a MyException is thrown, I want to handle the specific stuff to that exception but then I want to handle exceptions in general (catch (Exception ex)).

I don't want to use a finally-block and Java 7 Multi-catch is also no help here.

Any ideas how to handle this, I want to avoid redundant stuff in each catch-block. Is it better to catch Exception only and then use instanceof for my specific stuff?

Thanks.

like image 401
Michael Dietrich Avatar asked Oct 09 '13 08:10

Michael Dietrich


People also ask

Is it possible to rethrow a caught 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 there be two catch statements?

Yes, we can define one try block with multiple catch blocks in Java. Every try should and must be associated with at least one catch block.

What does it mean to Rethrow an exception?

Re-throwing an exception means calling the throw statement without an exception object, inside a catch block. It can only be used inside a catch block.

Does catch block Rethrow an exception in Java?

As you can see that in rethrow method, catch block is catching Exception but it's not part of throws clause. Java 7 compiler analyze the complete try block to check what types of exceptions are thrown and then rethrown from the catch block.


2 Answers

public void doStuff()
{
   try
   {

     // some exception can occur here

   } catch (MyException ex){

     // do something specific

     cleanupAfterException(ex);

   } catch (Exception ex) {

     cleanupAfterException(ex);
   }
}

private void cleanupAfterException(Exception ex)
{
   //Do your thing!
}

I presume something like this would do?

like image 103
René Jensen Avatar answered Sep 30 '22 17:09

René Jensen


You might want to try something like this:

try
{

}
catch(Exception ex)
{
    if(ex instanceof MyException)
    {
        // Do your specific stuff.
    }
    // Handle your normal stuff.
}
like image 39
ThaMe90 Avatar answered Sep 30 '22 18:09

ThaMe90