链接异常是一系列处理异常的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()还会继续链式异常。
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); } }
The takes us to the last.
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
以上是C# 中的链式异常的详细内容。更多信息请关注PHP中文网其他相关文章!