当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Why is outer "finally" not being executed when inner "catch" throws?

问题描述:

I wrote a simple program to test a theory that "finally" block will always execute no matter what.

But, what i'm seeing from the below pgm is that control never seems to enter the outer finaly block.

I tried doing F5 and also Ctrl-F5 in Visual studio and it's the same result.

Can someone explain why I'm seeing this behavior?

Output on the console window is :

inner catch

inner finally

outer catch

unhandled exeption:

..and then the app crashes

public class Program

{

static void Main()

{

try

{

try

{

string s = null;

s.ToString();

}

catch

{

Console.WriteLine("inner catch");

throw;

}

finally

{

Console.WriteLine("inner finally");

}

return;

}

catch

{

Console.WriteLine("outer catch");

throw;

}

finally

{

Console.WriteLine("outer finally");

}

}

}

网友答案:

The "outer finally" is run, just after the exception is handled.

Here is the output from running this code outside of the debugger:

inner catch
inner finally
outer catch

Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
   at SOConsole.Program.Main() in c:\Users\DaveShaw\Documents\Visual Studio 11\Pro
jects\SO\SOConsole\Program.cs:line 35
outer finally
Press any key to continue . . .

When the exception occurred the following was displayed:

After I clicked "Cancel", the application resumed and displayed the "outer finally".

If for some reason you close down your application before it has chance to enter the "outer finally" then you will never see you message. If an application's process is "terminated" then the finally's are skipped in case they contain code that prevents the application from closing. Otherwise it may be impossible to terminate that process.

网友答案:

The application is likely terminating before the stdout buffer is flushed.

Either add a break-point to the outer-finally (on the WriteLine) or throw a different exception from the outer-finally to confirm. A finally is not skipped: doing so would be a serious bug!

分享给朋友:
您可能感兴趣的文章:
随机阅读: