When is finally run if you throw an exception from the catch block?

后端 未结 7 1515
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 05:06
try {
   // Do stuff
}
catch (Exception e) {
   throw;
}
finally {
   // Clean up
}

In the above block when is the finally block called? Before the

相关标签:
7条回答
  • 2020-11-28 05:38

    Testing with a C# Console Application, the finally code has been executed after the exception is thrown: The "Application Error Dialog" existed and after you chose "Close the program" option, the finally block was executed in that console window. But setting the breaking point inside the finally code block, I can never hit it. The debugger keeps stopping at the throw statement. Here is my test code:

        class Program
        {
           static void Main(string[] args)
           {
              string msg;
              Console.WriteLine(string.Format("GetRandomNuber returned: {0}{1}", GetRandomNumber(out msg), msg) == "" ? "" : "An error has occurred: " + msg);
           }
    
           static int GetRandomNumber(out string errorMessage)
           {
             int result = 0;
             try
             {
                errorMessage = "";
                int test = 0;
                result = 3/test;
                return result;
             }
             catch (Exception ex)
             {
                errorMessage = ex.Message;
                throw ex;
    
             }
             finally
             {
                Console.WriteLine("finally block!");
             }
    
           }
        }
    

    Debugging in VS2010 - .NET Framework 4.0

    0 讨论(0)
提交回复
热议问题