Why use finally instead of code after catch

JavaTry Catch-Finally

Java Problem Overview


Why do this

} catch (SQLException sqle) {
    sqle.printStackTrace();
} finally {
    cs.close();
    rs.close();
}

Instead of this

} catch (SQLException sqle) {
    sqle.printStackTrace();
}
rs.close();
cs.close();

Java Solutions


Solution 1 - Java

Because if an exception gets thrown no code after the try block is executed unless the exception is caught. A finally block is always executed no matter what happens inside your try block.

Solution 2 - Java

Look at your catch block - it's going to throw DAOException. So the statements after your catch block aren't going to be executed even in the sample you've given. What you've shown (wrapping one exception in another) is one common pattern - but another possibility is that the catch block "accidentally" throws an exception, e.g. because one of the calls it makes fails.

Additionally, there may be other exceptions you don't catch - either because you've declared that the method throws them, or because they're unchecked exceptions. Do you really want to leak resources because an IllegalArgumentException got thrown somewhere?

Solution 3 - Java

Because if an exception is thrown,

  • Code in the finally clause will execute as the exception propagates outward, even if the exception aborts the rest of the method execution;

  • Code after the try/catch block will not get executed unless the exception is caught by a catch block and not rethrown.

Solution 4 - Java

According to HeadFirst Java, a finally block will run even if the try or catch block has a return statement. Flow jumps to finally and then back to return.

Solution 5 - Java

Because it ensures that the stuff in the finally block gets executed. Stuff after catch might not get executed, say, for example, there is another exception in the catch block, which is very possible. Or you just do what you did, and throw an exception wrapping the original exception.

Solution 6 - Java

The finally keyword guarantees that the code is executed. In your bottom example, the close statements are NOT executed. In the top example, they are executed (what you want!)

Solution 7 - Java

Your second approach won't do the 'close' statements because it is already left the method.

Solution 8 - Java

This is the way to avoid resource leaks

Solution 9 - Java

If you catch all errors, there should no difference, otherwise, only code inside finally block is executed because the code execution sequence is: finally code -> error throw -> code after catch hence, once your code throw any unhandled error, only finally code block works as expected.

Solution 10 - Java

The code in the finally block will get called before the exception is rethrown from the catch block. This ensures that any cleanup code that you've put in the finally block gets called. Code outside of the finally block will not be run.

Solution 11 - Java

Solution 12 - Java

consider the catch can throw an exception to the higher level functions in the call stack. This will lead calling final before throwing the exception to the upper level.

Solution 13 - Java

In http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html this is misleading (and may have originated the question):

The try block of the writeList method that you've been working with here opens a PrintWriter. The program should close that stream before exiting the writeList method. This poses a somewhat complicated problem because writeList's try block can exit in one of three ways.

1. The new FileWriter statement fails and throws an IOException.
2. The list.get(i) statement fails and throws an IndexOutOfBoundsException.
3. Everything succeeds and the try block exits normally.

The 4th way (an exception other than IOException and IndexOutOfBoundsException is thrown) is missing. The code depicted in the preceding page only catches (1) and (2) before resorting to finally.

I'm also new to Java and had the same questioning before finding this article. Latent memory tend to attach itself more to examples than to theory, in general.

Solution 14 - Java

The finally block may not always run, consider the following code.

public class Tester {
    public static void main(String[] args) {
        try {
            System.out.println("The main method has run");
            System.exit(1);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("The finally block has run");
        }
    }
}

In your case, I would suggest to wrap the code inside finally block into try/catch, as this code apparently may throw an exception.

    } catch (SQLException sqle) {
        sqle.printStackTrace();
    } finally {
     try {
        cs.close();
        rs.close();
     } catch (Exception e) {
      //handle new exception here
    }

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
Question124697View Question on Stackoverflow
Solution 1 - JavaJUST MY correct OPINIONView Answer on Stackoverflow
Solution 2 - JavaJon SkeetView Answer on Stackoverflow
Solution 3 - JavaBert FView Answer on Stackoverflow
Solution 4 - JavaAditi GargView Answer on Stackoverflow
Solution 5 - JavahvgotcodesView Answer on Stackoverflow
Solution 6 - JavaStarkeyView Answer on Stackoverflow
Solution 7 - JavanandaView Answer on Stackoverflow
Solution 8 - JavamtrautView Answer on Stackoverflow
Solution 9 - Javauser7537910View Answer on Stackoverflow
Solution 10 - JavaDoug MulleyView Answer on Stackoverflow
Solution 11 - JavarompetrollView Answer on Stackoverflow
Solution 12 - JavaMahmoud FayezView Answer on Stackoverflow
Solution 13 - JavaCallistusView Answer on Stackoverflow
Solution 14 - JavanomadusView Answer on Stackoverflow