try-catch语句讲解
try-catch 語句由一個 try 塊后跟一個或多個 catch 子句構成,這些子句指定不同的異常處理程序。 引發異常時,公共語言運行時 (CLR) 會查找處理此異常的 catch 語句。 如果當前執行的方法不包含這樣的 catch 塊,則 CLR 會查看調用當前方法的方法,然后會遍歷調用堆棧。 如果找不到 catch 塊,則 CLR 會向用戶顯示一條有關未經處理的異常的消息并停止執行程序。
try 塊包含可能導致異常的保護代碼。 該塊一直執行到引發異常或成功完成為止。 例如,下列強制轉換 null 對象的嘗試引發 NullReferenceException 異常:
object o2 = null; try {int i2 = (int)o2; // Error }雖然可以使用不帶參數的 catch 子句捕捉任何類型的異常,但不推薦這種用法。 通常,您應該只捕捉那些您知道如何從中恢復的異常。 因此,應該總是指定一個從 System.Exception 派生的對象參數。例如:
catch (InvalidCastException e) { }在同一個 try-catch 語句中可以使用一個以上的特定 catch 子句。 這種情況下 catch 子句的順序很重要,因為會按順序檢查 catch 子句。 將先捕獲特定程度較高的異常,而不是特定程度較小的異常。 如果對 catch 塊進行排序以使永遠不能達到后面的塊,編譯器將產生錯誤。
可在 catch 塊中使用 throw 語句以重新引發已由 catch 語句捕獲的異常。 以下示例從 IOException 異常中提取源信息,然后向父方法發送異常。
catch (FileNotFoundException e) {// FileNotFoundExceptions are handled here. } catch (IOException e) {// Extract some information from this exception, and then // throw it to the parent method.if (e.Source != null)Console.WriteLine("IOException source: {0}", e.Source);throw; }可捕獲一個異常并引發另一個異常。 執行此操作時,指定將其作為內部異常捕獲的異常,如下面的示例所示。
catch (InvalidCastException e) {// Perform some action here, and then throw a new exception.throw new YourCustomException("Put your error message here.", e); }還可以在指定的條件為真是重新引發異常,如下面的示例所示。
catch (InvalidCastException e) {if (e.Data == null){throw;}else{// Take some action.}}從內部一個 try 塊,只初始化其中聲明的變量。 否則,完成對塊的執行前,可能會發生異常。 例如,在下面的代碼示例中,變量 n 在 try 塊內初始化。 如果嘗試在 Write(n) 語句中的 try 塊外部使用此變量,則會生成編譯器錯誤。
static void Main() {int n;try {// Do not initialize this variable here.n = 123;}catch{}// Error: Use of unassigned local variable 'n'.Console.Write(n); }有關 catch 的更多信息,請參見 try-catch-finally。
示例在下面示例中,try 塊包含對可能導致異常的 ProcessString 方法的調用。 catch 子句包含僅在屏幕上顯示消息的異常處理程序。 當從 MyMethod 內部調用 throw 語句時,系統查找 catch 語句并顯示 Exception caught 消息。
C# class TryFinallyTest {static void ProcessString(string s){if (s == null){throw new ArgumentNullException();}}static void Main(){string s = null; // For demonstration purposes.try{ ProcessString(s);}catch (Exception e){Console.WriteLine("{0} Exception caught.", e);}} }/*Output:System.ArgumentNullException: Value cannot be null.at TryFinallyTest.Main() Exception caught.* */此例使用了兩個 catch 語句。 最先出現的最特定的異常被捕獲。
C# class ThrowTest3 {static void ProcessString(string s){if (s == null){throw new ArgumentNullException();}}static void Main(){try{string s = null;ProcessString(s);}// Most specific:catch (ArgumentNullException e){Console.WriteLine("{0} First exception caught.", e);}// Least specific:catch (Exception e){Console.WriteLine("{0} Second exception caught.", e);}} } /*Output:System.ArgumentNullException: Value cannot be null.at Test.ThrowTest3.ProcessString(String s) ... First exception caught. */在前面的示例中,如果從具體程度最低的 catch 子句開始,您將收到以下錯誤信息:
A previous catch clause already catches all exceptions of this or a super type ('System.Exception')
但是,若要捕獲特定程度最小的異常,請使用下面的語句替換 throw 語句:
throw new Exception();
C# 語言規范?
有關更多信息,請參見 C# 語言規范。C# 語言規范是 C# 語法和用法的權威資料。
請參見任務
如何:顯式引發異常參考
C# 關鍵字 try, catch, and throw Statements (C++) 異常處理語句(C# 參考) throw(C# 參考) try-finally(C# 參考)概念
C# 編程指南其他資源
C# 參考轉載于:https://www.cnblogs.com/milantgh/p/3654001.html
總結
以上是生活随笔為你收集整理的try-catch语句讲解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 非农行情的做单策略
- 下一篇: [转]Android 代码自动提示功能