finally块抛出新异常后,原Exception("1")为何消失?
关于C#中异常
throw new Exception("1")的去向疑问 代码示例
class Program { public static void Main() { try { Execute(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } public static void Execute() { try { Step3(); } catch (Exception ex) { Console.WriteLine("catch"); throw new Exception("1"); } finally { Console.WriteLine("finally"); throw new Exception("2"); } } public static void Step3() { try { Console.WriteLine("Step 3"); throw new Exception("step 3"); } finally { Console.WriteLine("Step 3 finally"); } } }
运行输出
Step 3 Step 3 finally catch finally 2
疑问
我无法理解代码中throw new Exception("1")的去向,它是否直接消失了?原因是什么?我已查阅相关规范,但仍不确定该异常的状态,它是否还存在于内存中?
解答
throw new Exception("1")确实被丢弃,不会继续传递:C#异常处理规则明确,当finally块中抛出新异常时,当前正在等待向上传递的异常会被直接替代,不再继续流转。- 具体流程拆解:
Step3抛出"step 3"异常,执行完自身finally块后,异常传递到Execute的catch块;Execute的catch块输出"catch"并抛出"1"异常,此时该异常准备向上传递,但程序必须优先执行finally块;Execute的finally块输出"finally"并抛出"2"异常,这一操作会直接覆盖之前的"1"异常,最终只有"2"异常会被Main的catch块捕获并输出。
- 内存状态:被丢弃的"1"异常对象会成为无引用对象,后续会被.NET的垃圾回收器(GC)回收,不会再驻留在内存中。
内容的提问来源于stack exchange,提问作者Alleshka
相关产品推荐
相关产品推荐

