try catch finally question(试着抓住最后的问题)
问题描述
在 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.
这篇关于试着抓住最后的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:试着抓住最后的问题


- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01