开发者

Why use finally instead of code after catch [duplicate]

This question already has answers here: 开发者_StackOverflow中文版 Why do we use finally blocks? [duplicate] (11 answers) Closed 5 years ago.

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();


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.


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?


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.


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.


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.


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!)


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


This is the way to avoid resource leaks


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.


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.


this might clarify: http://www.java2s.com/Code/Java/Language-Basics/Finallyisalwaysexecuted.htm


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.


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.


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
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜