Why do we use finally blocks?

2019-01-07 05:11发布

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

9条回答
一夜七次
2楼-- · 2019-01-07 05:32

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();
}
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-07 05:36

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

查看更多
我想做一个坏孩纸
4楼-- · 2019-01-07 05:38

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.

查看更多
时光不老,我们不散
5楼-- · 2019-01-07 05:39

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.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-01-07 05:40
  • 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.

查看更多
三岁会撩人
7楼-- · 2019-01-07 05:40

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

查看更多
登录 后发表回答