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

后端 未结 7 1553
没有蜡笔的小新
没有蜡笔的小新 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:37

    If there is an unhandled exception inside a catch handler block, the finally block gets called exactly zero times

      static void Main(string[] args)
      {
         try
         {
            Console.WriteLine("in the try");
            int d = 0;
            int k = 0 / d;
         }
         catch (Exception e)
         {
            Console.WriteLine("in the catch");
            throw;
         }
         finally
         {
            Console.WriteLine("In the finally");
         }
      }
    

    Output:

    C:\users\administrator\documents\TestExceptionNesting\bin\Release>TestExceptionNesting.exe

    in the try

    in the catch

    Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero. at TestExceptionNesting.Program.Main(String[] args) in C:\users\administrator\documents\TestExceptionNesting\TestExceptionNesting.cs:line 22

    C:\users\administrator\documents\TestExceptionNesting\bin\release>

    I got asked this question today at an interview and the interviewer kept going back "are you sure the finally doesn't get called?" I was uncertain if it was meant a trick question or the interviewer had something else in mind and wrote the wrong code for me to debug so I came home and tried it (build and run, no debugger interaction), just to put my mind at rest.

提交回复
热议问题