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

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

    Why not try it:

    outer try
    inner try
    inner catch
    inner finally
    outer catch
    outer finally
    

    with code (formatted for vertical space):

    static void Main() {
        try {
            Console.WriteLine("outer try");
            DoIt();
        } catch {
            Console.WriteLine("outer catch");
            // swallow
        } finally {
            Console.WriteLine("outer finally");
        }
    }
    static void DoIt() {
        try {
            Console.WriteLine("inner try");
            int i = 0;
            Console.WriteLine(12 / i); // oops
        } catch (Exception e) {
            Console.WriteLine("inner catch");
            throw e; // or "throw", or "throw anything"
        } finally {
            Console.WriteLine("inner finally");
        }
    }
    

提交回复
热议问题