试着抓住最后的问题
- 作者: 殇lss狂
- 来源: 51数据库
- 2023-02-08
问题描述
在 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#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源