试着抓住最后的问题

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)