CodeBlue
CodeBlue

Reputation: 15409

How to throw from the finally clause an exception caught in the catch clause?

Is it possible without using an additional variable to find out what exception was caught in the catch clause and then throw it again from the finally clause?

public void exceptionalFunction() throws Exception
 {
    try
     {
         // exception causing code
     }
    catch (TypeAException e)
     {
        // exception specific logic
     }
    catch (TypeBException e)
     {
         // exception specific logic        
     }
    catch (TypeCException e)
     {
        // exception specific logic        
     }
    finally
     {
         // throw the exception that was caught, if one was caught. 
     }
 }

Upvotes: 2

Views: 195

Answers (3)

absentmindeduk
absentmindeduk

Reputation: 136

I have to agree with tibtof.

It makes no sense to re-throw the exception in a finally block versus doing it after the implementation logic of each catch block - you gain nothing by doing so. So his is the correct solution.

Generally speaking it is better to do it in this manner as you can extend this by declaring more specific exceptions each time and passing these back up the call stack each time - by creating your own custom exception type and doing:

catch (TypeAException e) 
{ 
    // exception specific logic  
    throw new myCustomException("Custom message " + e.getMessage);      
} 

each time.

Hope that helps.

Upvotes: 1

Jit B
Jit B

Reputation: 1246

You cannot catch them in the finally clause. the scope of catch and finally are separate. But since you do not want to write multiple exception handling codes, I'd suggest you use the features introduced in Java 7.

....
....
catch (Exception1|Exception2|Exception2 e){
    //determine type and handle accordingly
}

If you are using java6 or earlier, the only way to save coding efforts is to handle them via a method.

....
....
catch(Exception1 e){
    handle(e);
}
catch(Exception2 e){
    handle(e);
}

then you can use instanceof to determine the type of exception and do your thing.

Upvotes: 2

tibtof
tibtof

Reputation: 7967

Not without using an additional variable. Without using an additional variable you could only throw again the exception after the exception specific logic:

catch (TypeAException e)
{
    // exception specific logic 
    throw e;       
}
catch (TypeBException e)
{
    // exception specific logic 
    throw e;       
}
catch (TypeCException e)
{
    // exception specific logic 
    throw e;       
}

Upvotes: 6

Related Questions