无论是内部的finally块被执行(几乎)总是,那么什么是包code进去或离开之间的区别是没有结束的?
Whatever is inside finally blocks is executed (almost) always, so what's the difference between enclosing code into it or leaving it unclosed?
推荐答案finally块内的code将获得无论是否有一个例外执行。这是非常方便的,当涉及到你需要总是喜欢关闭连接运行某些内务功能。
The code inside a finally block will get executed regardless of whether or not there is an exception. This comes in very handy when it comes to certain housekeeping functions you need to always run like closing connections.
现在,我的猜测的你的问题是,为什么你应该这样做:
Now, I'm guessing your question is why you should do this:
try { doSomething(); } catch { catchSomething(); } finally { alwaysDoThis(); }当你可以做到这一点:
try { doSomething(); } catch { catchSomething(); } alwaysDoThis();答案是,有很多次你的catch语句里面的code要么重新抛出异常或打破当前的功能。后者code时,alwaysDoThis();如果catch语句里面的code问题退货或抛出一个新的异常呼叫将不会执行。
The answer is that a lot of times the code inside your catch statement will either rethrow an exception or break out of the current function. With the latter code, the "alwaysDoThis();" call won't execute if the code inside the catch statement issues a return or throws a new exception.
更多推荐
为什么要在C#中最后使用?
发布评论