Why do we use finally blocks?

Java.NetFinally

Java Problem Overview


As far as I can tell, both of the following code snippets will serve the same purpose. Why have finally blocks at all?

Code A:

try { /* Some code */ }
catch { /* Exception handling code */ }
finally { /* Cleanup code */ }

Code B:

try { /* Some code */ }
catch { /* Exception handling code */ }
// Cleanup code

Java Solutions


Solution 1 - Java

  • What happens if an exception you're not handling gets thrown? (I hope you're not catching Throwable...)
  • What happens if you return from inside the try block?
  • What happens if the catch block throws an exception?

A finally block makes sure that however you exit that block (modulo a few ways of aborting the whole process explicitly), it will get executed. That's important for deterministic cleanup of resources.

Solution 2 - Java

Note that (in Java at least, probably also in C#) it's also possible to have a try block without a catch, but with a finally. When an exception happens in the try block, the code in the finally block is run before the exception is thrown higher up:

InputStream in = new FileInputStream("somefile.xyz");
try {
    somethingThatMightThrowAnException();
}
finally {
    // cleanup here
    in.close();
}

Solution 3 - Java

You may want to put the code that you want to anyway get executed irrespective of what happens in your try or catch block.

Also if you are using multiple catch and if you want to put some code which is common for all the catch blocks this would be a place to put- but you cannot be sure that the entire code in try has been executed.

For example:

conn c1 = new connection();
try {
    c1.dosomething();
} catch (ExceptionA exa) {
    handleexA();
    //c1.close();
} catch (ExceptionB exb) {
    handleexB();
    //c1.close();
} finally {
    c1.close();
}

Solution 4 - Java

Finally always gets executed, where as your code after the catch may not.

Solution 5 - Java

Even though our application is closed forcefully there will be some tasks, which we must execute (like memory release, closing database, release lock, etc), if you write these lines of code in the finally block it will execute whether an exception is thrown or not...

Your application may be a collection of threads, Exception terminates the thread but not the whole application, in this case finally is more useful.

In some cases finally won't execute such as JVM Fail, Thread terminate, etc.

Solution 6 - Java

Because you need that code to execute regardless of any exceptions that may be thrown. For example, you may need to clean up some unmanaged resource (the 'using' construct compiles to a try/finally block).

Solution 7 - Java

Still scrolling down? Here you go!

This question gave me tough time back a while.

try
{
 int a=1;
 int b=0;
 int c=a/b;
}
catch(Exception ex)
{
 console.writeline(ex.Message);
}
finally
{
 console.writeline("Finally block");
}
console.writeline("After finally");

what would be printed in the above scenario? Yes guessed it right:

  • ex.Message--whatever it is (probably attempted division by zero)

  • Finally block

  • After finally

     try
     {
         int a=1;
         int b=0;
         int c=a/b;
     }
     catch(Exception ex)
     {
         throw(ex);
     }
     finally
     {
         console.writeline("Finally block");
     }
     console.writeline("After finally");
    

What would this print? Nothing! It throws an error since the catch block raised an error.

In a good programming structure, your exceptions would be funneled, in the sense that this code will be handled from another layer. To stimulate such a case i'll nested try this code.

try
{    
 try
    {
     int a=1;
     int b=0;
     int c=a/b;
    }
    catch(Exception ex)
    {
     throw(ex);
    }
    finally
    {
     console.writeline("Finally block")
    }
    console.writeline("After finally");
}
catch(Exception ex)
{
 console.writeline(ex.Message);
}

In this case the output would be:

  • Finally block
  • ex.Message--whatever it is.

It is clear that when you catch an exception and throw it again into other layers(Funneling), the code after throw does not get executed. It acts similar to just how a return inside a function works.

You now know why not to close your resources on codes after the catch block.Place them in finally block.

Solution 8 - Java

finally ALWAYS executes, unless the JVM was shut down, finally just provides a method to put the cleanup code in one place.

It would be too tedious if you had to put the clean up code in each of the catch blocks.

Solution 9 - Java

There may be times when you want to execute a piece of code no matter what. Whether an exception is thrown or not. Then one uses finally.

Solution 10 - Java

If catch block throws any exception then remaining code will not executed hence we have to write finaly block.

Solution 11 - Java

finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.


The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMohammad NadeemView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaJesperView Answer on Stackoverflow
Solution 3 - JavaBalaji NatesanView Answer on Stackoverflow
Solution 4 - JavaSrulyView Answer on Stackoverflow
Solution 5 - JavaSandeep PView Answer on Stackoverflow
Solution 6 - JavaEd S.View Answer on Stackoverflow
Solution 7 - JavaAshique razakView Answer on Stackoverflow
Solution 8 - JavaMahmoud HanafyView Answer on Stackoverflow
Solution 9 - JavaEgalitarianView Answer on Stackoverflow
Solution 10 - JavaReshma KoreView Answer on Stackoverflow
Solution 11 - JavaAakersh SharmaView Answer on Stackoverflow