C# Time of finally execution

后端 未结 9 1607
情话喂你
情话喂你 2021-02-04 01:37

Take this code:

using System;

namespace OddThrow
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
              


        
9条回答
  •  日久生厌
    2021-02-04 02:04

    Although not completely expected, the program does behave as it should. A finally block is not expected to be run first, it is only expected to be run always.

    I adjusted your sample:

    public static void Main()
    {
        try
        {
            Console.WriteLine("Before throwing");
            throw new Exception("Exception!");
        }
        finally
        {
            Console.WriteLine("In finally");
            Console.ReadLine();
        }
    }
    

    In this case you will get the nasty unhandled exception dialog, but afterwards the console will output and wait for input, thus executing the finally, just not before windows itself catches the unhandled exception.

提交回复
热议问题