0

This example took from the official documentation does not behave as it says (does not execute the finally) because it just prints:

Unhandled exception. System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'. at ThrowTestA.Main() in C:\repos\Sandbox\Console\Console\Program.cs:line 14

using System;

public class ThrowTestA
{
    public 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
}

This is my Program project:

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

</Project>
user33276346
  • 1,501
  • 1
  • 19
  • 38
  • Did you follow the directions? The text right there in the sample tells you the finally block won't run unless you click cancel on the dialog. – John Lord Dec 14 '22 at 19:09
  • There is no cancel – user33276346 Dec 14 '22 at 19:17
  • Visual Studio 2022 Community using the Debug profile https://i.imgur.com/bnsNCxB.png – user33276346 Dec 14 '22 at 19:29
  • The screenshot tells that you are executing the program with debugging so it breaks at the exception. Just try to execute it without debugging (Ctrl+F5 by default) and see what happens. But it's actually written also in the comment of your posted code. – György Kőszeg Dec 14 '22 at 21:09
  • Thank you, now it works as expected. Why did it work without debugging and not while debugging? – user33276346 Dec 14 '22 at 22:03
  • @GyörgyKőszeg any idea? – user33276346 Dec 16 '22 at 01:46
  • @user33276346: By default the debugger breaks at exceptions, even if they are handled in `try`..`catch`. In Exception Settings you can turn off individual exceptions (`InvalidCastException` in our case). But since there is no `catch` block in your code the debugger will break at the exception anyway because an unhandled top-level exception makes the application crash (and thus detach the debugger). – György Kőszeg Dec 16 '22 at 11:19

0 Answers0