Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does finally completely execute if an exception is thrown within finally block

so I have a bit of code here and I'm not sure entirely how it would react in the event that the reader.close() method throws an exception.

public void someMethod(String s) throws IOException{
   BufferedReader reader = Files.newBufferedReader(filePath,cs);
   listRWLock.readLock().lock();
   try{
     //miscellaneous code involving reading
   }finally{
     reader.close()
     listRWLock.readLock().unlock()
   }
}

ListRWLock is a ReentrantReadWriteLock. In the event that the reader.close() method throws an exception, would the statement after it fail to execute? I've tried searching for the topic, and while I've gotten something about finally executing in the event of return statements, I haven't managed to find details on what happens if an exception is thrown within the finally block.

Thanks in advance.

like image 485
ElvenAshwin Avatar asked Sep 28 '14 05:09

ElvenAshwin


People also ask

What happens if an exception is thrown in finally block?

The "finally" block execution stops at the point where the exception is thrown. Irrespective of whether there is an exception or not "finally" block is guaranteed to execute. Then the original exception that occurred in the try block is lost.

Does finally always get executed?

A finally block is always get executed whether the exception has occurred or not. If an exception occurs like closing a file or DB connection, then the finally block is used to clean up the code.

Will finally block execute?

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

In which condition will the finally block not be executed?

Condition where finally block is not executed in Java When the System. exit() method is called in the try block before the execution of finally block, finally block will not be executed.


2 Answers

Basically, finally clauses are there to ensure proper release of a resource. However, if an exception is thrown inside the finally block, that guarantee goes away.

An issue for which there's no really neat solution is that code in the finally block could itself throw an exception. In this case, the exception in the finally block would be thrown from the exception instead of any exception occurring inside the try block. Since code in the finally block is intended to be "cleanup" code, we could decide to treat exceptions occurring there as secondary, and to put an excplicit catch:

public int readNumber(File f) throws IOException, NumberFormatException {
  BufferedReader br = new BufferedReader(new
    InputStreamReader(new FileInputStream(f), "ASCII"));
  try {
    return Integer.parseInt(br.readLine());
  } finally {
    try { br.close(); } catch (IOException e) {
      // possibly log e
    }
  }
}

Some other things to note about finally blocks:

  1. The same 'overriding' problem that we mentioned with exceptions occurs when returning a value from a finally block: this would override any return value that the code in the try block wanted to return. In practice, returning a value from a finally clause is rare and not recommended.
  2. Actually exiting the program (either by calling System.exit() or by causing a fatal error that causes the process to abort: sometimes referred to informally as a "hotspot" or "Dr Watson" in Windows) will prevent your finally block from being executed!
  3. There's nothing to stop us nesting try/catch/finally blocks (for example, putting a try/finally block inside a try/catch block, or vice versa), and it's not such an uncommon thing to do.
like image 197
Pert8S Avatar answered Oct 23 '22 17:10

Pert8S


You can do something like this:

try{
    //miscellaneous code involving reading
}finally{
   handlePossibleException(reader);
   listRWLock.readLock().unlock()
}

handlePossibleException(BufferedReader reader) {
    try {
         if (reader != null) {
             reader.close();
         }
    } catch( Exception e ) {
      log.e( "reader.close() Exception: ", e );
      }
} 
like image 36
Vikas Avatar answered Oct 23 '22 18:10

Vikas