0

Here Microsoft says:

"By using a finally block, you can clean up any resources that are allocated in a try block, and you can run code even if an exception occurs in the try block."

and clearly use this sample to support that idea:

public class ThrowTestA
{
    static void Main()
    {
        int i = 123;
        string s = "Some string";
        object obj = s;

        try
        {
            // Invalid conversion; obj contains a string, not a numeric type.
            i = (int)obj;

            // The following statement is not run.
            Console.WriteLine("WriteLine at the end of the try block.");
        }
        finally
        {
            // To run the program in Visual Studio, type CTRL+F5. Then
            // click Cancel in the error dialog.
            Console.WriteLine("\nExecution of the finally block after an unhandled\n" +
                "error depends on how the exception unwind operation is triggered.");
            Console.WriteLine("i = {0}", i);
        }
    }
    // Output:
    // Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
    //
    // Execution of the finally block after an unhandled
    // error depends on how the exception unwind operation is triggered.
    // i = 123
}

but when I copied this to my .Net-Core console it doesn't execute finally and doesn't return the output in finally that I expect according to Microsoft says! it returns below and I don't know why!

enter image description here

I know that we can simply use try..catch block and resolve the problem. I just want to know this contradiction with Microsoft's sample and my experience!

Mohammad
  • 1,197
  • 2
  • 13
  • 30
  • I did it, but nothing is changed – Mohammad Oct 22 '20 at 12:35
  • 3
    Add a ```catch {}``` block between your ```try {}``` and ```finally {}``` section. – devsmn Oct 22 '20 at 12:38
  • @imsmn I know and it's so simple! but I just investigated on Finally block behavior. why we have to use it? we can simply remove it and do whatever we want after catch! like free resource and forth – Mohammad Oct 22 '20 at 12:47

2 Answers2

4

And later on in the same paper they say

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.

in your case the exception is unhandled so finally is not guaranteed to be called

mishmashru
  • 459
  • 5
  • 8
0

Check it here:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-finally

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.

Usually, when an unhandled exception ends an application, whether or not the finally block is run is not important. However, if you have statements in a finally block that must be run even in that situation, one solution is to add a catch block to the try-finally statement. Alternatively, you can catch the exception that might be thrown in the try block of a try-finally statement higher up the call stack. That is, you can catch the exception in the method that calls the method that contains the try-finally statement, or in the method that calls that method, or in any method in the call stack. If the exception is not caught, execution of the finally block depends on whether the operating system chooses to trigger an exception unwind operation.

When is this usually?

If the exception is not caught, execution of the finally block depends on whether the operating system chooses to trigger an exception unwind operation.

Exception unwind

When we enclose a block of code with a try statement compiler creates a step to store current context of the CPU in current stack frame with program counter pointed to start of catch block. If the CPU encounters any error it retrieves the context from stack an program counter jumps to catch statement.

Conditions when finally does not execute in a .net try..finally block

Some examples:

  • StackOverflowException
  • ExecutionEngineException
  • Application exit
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
  • so, with this description why do we use finally block? we just can remove it and behave whatever we want after catch block (for example release resource and so on). why we have to use finally? What's its job? – Mohammad Oct 22 '20 at 12:44
  • 1
    @Mohammad [see](https://stackoverflow.com/questions/547791/why-use-finally-in-c) – Trevor Oct 22 '20 at 12:52
  • 1
    Check this one here: https://stackoverflow.com/questions/111597/conditions-when-finally-does-not-execute-in-a-net-try-finally-block – Athanasios Kataras Oct 22 '20 at 13:03