试着抓住最后的问题 [英] try catch finally question

查看:19
本文介绍了试着抓住最后的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Try Catch finally 块中,finally 块是否始终执行,或者仅在 catch 块不返回错误时执行?

In a Try Catch Finally block, does the finally block always execute no matter what, or only if the catch block does not return an error?

我的印象是 finally 块只有在 catch 块通过且没有错误的情况下才会执行.如果catch块因为错误而被执行,是不是应该一起停止执行并返回错误信息(如果有)?

I was under the impression that the finally block only executes if the catch block passes without errors. If the catch block is executed because of an error, shouldn't it stop execution all together and return the error message if any?

推荐答案

不仅 finally 块会在 catch 块之后执行,try 甚至不需要捕获任何异常来执行 finally.以下是完全合法的代码:

Not only will a finally block execute following a catch block, try does not even require that any exception be caught for the finally to execute. The following is perfectly legal code:

try 
{
//do stuff
}
finally 
{
   //clean up
}

实际上,当 catch 块包含以下内容时,我继承了一些代码中的 catch 块:

I actually took out the catch blocks in some code I inherited when the catch block consisted of:

catch(Exception ex)
{
   throw ex;
}

在这种情况下,所需要做的只是清理,所以我只留下了一个 try{} 和 finally{} 块,让异常冒泡并保持其堆栈跟踪完好无损.

In that case, all that was required was to clean up, so I left it with just a try{} and finally{} block and let exceptions bubble up with their stack trace intact.

这篇关于试着抓住最后的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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