Benefits of the "finally" clause in exception handling

556 views Asked by At

Being a novice in this this, what's the benefits of using the finally clause in exception handling. Or in otherwords, when it's best to use it and when it's best not use it.

The only one that I can think of is closing an input/output stream ...any other benefits ???!!

5

There are 5 answers

3
Jatin Khurana On BEST ANSWER

Whatever StinePike has written is perfect but I want to add something in that.

Finally block is executed either exception occurs or not.... so we can achieve this without finally block by writing the finally block code in try block and also in catch block(). Now if exception doesn't occur, it execute the code from try block.If exception occurs, it execute the code from catch block.

So the additional advantage from the finally block is that you can write return statement anywhere in the method, still finally block is executed but the code is not executed if you don't write the code in finally block and return from the method(on the basis of some condition) before reaching to that code.

4
Konstantin Yovkov On

The finally is very useful in the cases in which some resources need to be released.

For example:

InputStream is = null;
try {
    is = new FileInputStream("C://test.txt");
    //some reading-file logic 
} catch (Exception e) {
    //exception handling
} finally {
    //releasing the resources (closing the input stream)
    if (is != null) {
        is.close();
    }
}
0
stinepike On

For any kind of tasks that you want to do whenever all tasks are finished , the finally block is useful. Here by the final tasks I refer to any of the folowwings. releasing resources, closing streams, completing your own ending tasks of any operations etc.

As we know the finally block always executes even after any exception. so the operations in the finally block are gurranteed. so these are the tasks those should be done in finally.

0
Raffaele Rossi On

You've already thought about a good example. Closing I/O streams or, more generally freeing/release any kind of resource you've previously opened/created.

Another example might be terminates a process/thread you might have created.

Even more, you might send events/notifications to client components.

1
supercat On

Another situation where finally is useful is to ensure that "manual" locks get released (locks implemented with the language's synchronizing structures internally use finally for this purpose). When doing this, however, there is a detail which is sometimes overlooked: locks are often acquired for the purpose of allowing code to momentarily violate an object's invariants and re-establish them before anyone else can notice. If an exception occurs which would leave an object's invariants in an improper state, the proper behavior is generally not to leave the lock held, but rather ensure that a variable is set to indicate that has occurred, and have anyone that acquires the lock check this variable and throw an exception if it is set.

If one encapsulates the lock-is-valid variable within the lock object, the code might look like:

void insertItem(...)
{
  try
  {
    myLock.acquire();
    myLock.enterDanger();
    ...
    myLock.leaveDanger();
  }
  finally
  {
    myLock.release();
  }
}

Code which never modifies the guarded object but simply reads it would never have to "enterDanger". If release gets called while the lock is still indanger state, it may wish to capture the current stack trace; pending or future calls to myLock.acquire should throw an exception, possibly including that stack trace as supplemental information.

Note that one could try instead to invalidate myLock within a catch block, but one must then ensure that nobody adds a catch block to the try block to handle expected exceptions without invalidating the lock. If an expected exception occurs in an unexpected place, the guarded object might be left in a corrupt state without triggering the catch that was supposed to invalidate it (the execution of the more specific catch would prevent execution of the less-specific one).