我读到 finally
键使 try-catch
block 最终工作,甚至函数是否抛出异常。但我想知道如果我不将代码放在 finally
block (如下面的 Function_2)中会有什么不同,这是我用来编码的方式。谢谢!
void Function_1()
{
try
{
throw new Exception();
}
catch
{
}
finally //Have finally block
{
Other_Function();
}
}
void Function_2()
{
try
{
throw new Exception();
}
catch
{
}
Other_Function(); //Don't have finally block
}
最佳答案
if I dont put a code inside a finally block (like Function_2 below)
如果你不把代码放在 finally
中,除非你不会得到异常,否则代码块将被执行。
但是如果您在该代码块(未保留在 finally 中)将不会执行之前遇到异常,因为控件本身会从那里返回。
但是如果你把你的代码放在 finally
中,不管情况如何,它都会被执行。
示例:1 没有 finally block
try
{
//throw exption
}
catch
{
//return from here
}
//below statement won't get executed
Other_Function();
Example:2 with finally block
try
{
//throw exption
}
catch
{
//return from here if finally block is not available
//if available execute finally block and return
}
finally
{
//below statement surly gets executed
Other_Function();
}
关于c# - 解释 "finally"在 try-catch-finally block 中的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20297516/