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.
这篇关于试着抓住最后的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:试着抓住最后的问题
基础教程推荐
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01