Search code examples
javatry-catch-finally

Java try catch finally seems pointless


This is a quite silly question but i don't understand the combined use of catch and finally. As far as i know the code after a catch block will be executed whether or not an exception will be raised, so why using

try
{
    doSomething();
}
catch(Exception e)
{
    e.printStackTrace();
}
finally
{
    doSomethingInFinally();
}

instead of

try
{
    doSomething();
}
catch(Exception e)
{
    e.printStackTrace();
}

doSomethingInFinally();

? I always see people using the first pattern but i think it is extra code.


Solution

  • There are cases where your suggestion doesn't work

    • There is no catch statement at all (the method will not continue executing if an exception is thrown).

    • The catch block re-throws the exception.

    • There is a return statement in the try block.
    • The catch statement doesn't handle the super-type exception (like Throwable in your case).