C# 中的连锁异常
连锁异常是一串用 try-catch 语句处理异常的代码。要创建一个连锁异常,即连锁异常,_
设置第一个 try-catch −
示例
static void Main(string[] args) { try { One(); } catch (Exception e) { Console.WriteLine(e); } }
现在在 One() 方法下 try-catch −
示例
static void One() { try { Two(); } catch (Exception e) { throw new Exception("First exception!", e); } }
Two() 方法也继续连锁异常。
Learn C# in-depth with real-world projects through our C# certification course. Enroll and become a certified expert to boost your career.
示例
static void Two() { try { Three(); } catch (Exception e) { throw new Exception("Second Exception!", e); } }
现在是下一个方法。
示例
static void Three() { try { Last(); } catch (Exception e) { throw new Exception("Third Exception!", e); } }
这将我们带到最后。
示例
static void Last() { throw new Exception("Last exception!"); }
运行上述代码后,异常将如下处理 −
System.Exception: First exception! ---< System.Exception: Middle Exception! ---< System.Exception: Last exception! at Demo.Two () [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0 --- End of inner exception stack trace --- at Demo.Two () [0x00016] in <199744cb72714131b4f5995ddd1a021f>:0 at Demo.One () [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0 --- End of inner exception stack trace --- at Demo.One () [0x00016] in <199744cb72714131b4f5995ddd1a021f>:0 at Demo.Main (System.String[] args) [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0
广告