在try catch / finally语句中finally的意义是什么 [英] What is the point of finally in a try catch/except finally statement

查看:395
本文介绍了在try catch / finally语句中finally的意义是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多年来,我已经在多种语言中使用了try-catch / except-finally变体,今天有人问我,最终的意义是什么,我无法回答。

I have used try-catch/except-finally variants in many languages for years, today someone asked me what is the point of finally and I couldn't answer.

基本上,您为什么要在最后放入一条语句,而不是只在整个try-catch块之后放一条语句?换句话说,以下代码块之间是有区别的:

Basically why would you put a statement in finally instead of just putting it after the whole try-catch block? Or in other words is there a difference between the following blocks of code:

try{ //a}
catch {//b}
finally {//c}


try{//a}
catch{//b}
//c

编辑:

人们,我知道最后会做什么,我一直在使用它已经存在了很长时间,但是我的问题是在上面的示例中,最后将 // c 放入似乎不是吗?


PEOPLE, I know what finally does, I have been using it for ages, but my question is in the above example putting //c in finally seems redundant, doesn't it?

推荐答案

最终块的目的是确保代码在三种情况下运行,而这种情况不会很干净地处理。单独使用捕获块:

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. 如果 try 块中的代码通过退出返回
  2. 如果 catch 块中的代码要么抛出捕获的异常,要么-偶然地或故意-最终抛出一个新的。
  3. 如果 try 块中的代码遇到一个没有捕获的异常。
  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.

一个人可以在每次返回之前复制 finally 代码或throw,并将 catch 块包装在自己的try / catch中,以允许发生意外异常的可能性,但是要避免所有这些和只需使用 finally 块。

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,我希望语言设计者可以包括的一件事是<$ c finally 块的$ c> exception 参数,以处理需要在异常后进行清理但仍希望其渗透的情况(例如,可以将构造函数的代码包装在这样的构造中,如果构造函数要异常退出,则 Dispose 正在构造的对象)。

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

这篇关于在try catch / finally语句中finally的意义是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆