为什么这个“最后”执行? [英] Why does this "finally" execute?
本文介绍了为什么这个“最后”执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果您运行下面的代码,它将在每次调用goto后实际执行:
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 do you expect it to not execute?
如果您尝试/ catch / finally或try / 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,考虑'return'。
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屋!
查看全文