Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immediately rethrowing in catch block and using finally

I have a wrapper responsible for logging operations, named OperationWrapper. Its structure is simple and as follows:

public void runOperation(Operation o) throws Exception{ 
     logOperationStarted();
     o.execute();
     logOperationFinished();
}

Since the "o" operation can throw an exception, the logOperationFinished() method will not always be called and thus logging does not operate correctly.

Also, various components invoking the runOperation() method handle these exceptions .

Having wanted to ensure that logOperationFinished() will always run, I implemented the following structure:

public void runOperation(Operation o) throws Exception{ 
     logOperationStarted();
     try{
       o.execute();
     }
     catch(Exception e){
       throw e; 
     }
     finally{
       logOperationFinished();
     }
}

Now logOperationFinished() does always run, but I am getting a warning from IntelliJ:

Caught exception is immediately rethrown
Reports any catch block where the caught exception is immediately rethrown, without performing any action on it. Such catch blocks are unnecessary or lack error handling.

To me it seems the IntelliJ is not taking the finally block into account when issuing this warning.

Am I doing something wrong or is there a better way of achieving this?

Thanks.

like image 867
Shahar Avatar asked Apr 07 '15 05:04

Shahar


3 Answers

yes, you do not need the catch

public void runOperation(Operation o) throws Exception{ 
     logOperationStarted();
     try{
       o.execute();
     }
     finally{
       logOperationFinished();
     }
}
like image 95
Scary Wombat Avatar answered Oct 28 '22 20:10

Scary Wombat


Use try-finally block from JLS 14.20.2. Execution of try-finally

If execution of the try block completes abruptly for any other reason R, then the finally block is executed, and then there is a choice:

  1. If the finally block completes normally, then the try statement completes abruptly for reason R.

  2. If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).

public void runOperation(Operation o) throws Exception{ 
     logOperationStarted();
     try{
        o.execute();
     }finally{
       logOperationFinished();
     }
}

If you want to use try-catch-finally still not a problem you can ignore warning from IntelliJ, or throw new exception from catch block.

throw new ExceptionYouWantToThrow(e);
like image 2
Sumit Singh Avatar answered Oct 28 '22 20:10

Sumit Singh


Is the exception meant to be recoverable? If not, it may be appropriate to throw an error, rather than rethrow the exception.

Scary Wombat's answer is most likely what you are after though.

throw new Error(e);

Exception vs Error

like image 2
user2469515 Avatar answered Oct 28 '22 19:10

user2469515