What is the point of finally in a try catch/except finally statement

断了今生、忘了曾经 提交于 2019-12-02 17:14:07

The purpose of a finally block is to ensure that code gets run in three circumstances which would not very cleanly be handled using "catch" blocks alone:

  1. If code within the `try` block exits via `return`
  2. If code within a catch block either rethrows the caught exception, or--accidentally or intentionally--ends up throwing a new one.
  3. If the code within the `try` block encounters an exception for which there is no catch.

One could copy the finally code before every return or throw, and wrap catch blocks within their own try/catch to allow for the possibility of an accidental exception occurring, but it's far easier to forgo all that and simply use a finally block.

BTW, one thing I wish language designers would include would be an exception argument to the finally block, to deal with the case where one needs to clean up after an exception but still wants it to percolate up the call stack (e.g. one could wrap the code for a constructor in such a construct, and Dispose the object under construction if the constructor was going to exit with an exception).

Finally block is executed even if an exception thrown in the try block. Therefore, for instance if you opened a stream before, you may want to close that stream either an exception is thrown or not. Finally block is useful for such an issue.

Massimiliano Peluso

Finally make sure your code is executed even if you get an exception.

The finally block is useful for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception

http://msdn.microsoft.com/en-us/library/zwc8s4fz(v=vs.80).aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!