C# 中的链式异常

csharpprogrammingserver side programming更新于 2025/9/19 1:22:00

链式异常是处理异常的 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);
   }
}

这将带我们到最后一个。

示例

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

相关文章