为什么这"最后"执行? [英] Why does this "finally" execute?
本文介绍了为什么这"最后"执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果您运行下面的代码终于每次调用跳转后实际执行的:
If you run the code below it actually executes the finally after every call to the goto:
int i = 0;
Found:
i++;
try
{
throw new Exception();
}
catch (Exception)
{
goto Found;
}
finally
{
Console.Write("{0}\t", i);
}
为什么?
Why?
推荐答案
为什么你期望它没有执行?
Why do you expect it to not execute?
如果你的try / catch / finally或try / finally块,执行finally代码<击>无论你可能有什么样的代码在try或catch块罢工>的大部分时间的。
If you have try/catch/finally or try/finally block, finally block executes no matter what code you may have in the try or catch block most of the time.
相反goto语句,可以考虑回归。
Instead of goto, consider 'return'.
//imagine this try/catch/finally block is inside a function with return type of bool.
try
{
throw new Exception();
}
catch (Exception)
{
return false; //Let's say you put a return here, finally block still executes.
}
finally
{
Console.WriteLine("I am in finally!");
}
这篇关于为什么这"最后"执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文