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() 方法也會持續鏈式異常。
示例
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP