2021年3月31日星期三

Does finally block execute if there is an unhandled exception?

We know that the code in the finally block is guaranteed to execute, regardless of whether the exception is caught. But let's say we have the following code:

class Program {     static void Main(string[] args) {        try {           int a = 0;           int b = 2021 / a;        }        finally {           System.Diagnostics.Debug.WriteLine("finally execute");        }     }  }  

I cannot use Console.WriteLine since an unhandled exception terminates a process, no output written to the console, so I use System.Diagnostics.Debug.WriteLine, hopefully I can see "finally execute" displayed in the VS debug window.

When I execute the code, I didn't find "finally execute" in debug window, which means finally block won't execute if there is an unhandled exception.

If you look at this link https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-finally

It does say:

Part one

Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered. That, in turn, is dependent on how your computer is set up.

Part Two

The only cases where finally clauses don't run involve a program being immediately stopped. An example of this would be when InvalidProgramException gets thrown because of the IL statements being corrupt. On most operating systems, reasonable resource cleanup will take place as part of stopping and unloading the process.

My questions are:

Q1-What does "dependent on how your computer is set up" in Part One mean?

Q2-If it is dependent on how the computer is set up, then what does Part Two mean? The exception in my example is DivideByZeroException, not InvalidProgramException, so why the finllay block still doesn't execute

https://stackoverflow.com/questions/66897869/does-finally-block-execute-if-there-is-an-unhandled-exception April 01, 2021 at 11:00AM

没有评论:

发表评论