<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # try-catch(C# 參考) Try-catch 語句包含一個后接一個或多個 **catch** 子句的 **try** 塊,這些子句指定不同異常的處理程序。 ## 備注 引發異常時,公共語言運行時 (CLR) 查找處理此異常的 **catch** 語句。如果當前正在執行的方法不包含此類 **catch** 塊,則 CLR 查看調用了當前方法的方法,并以此類推遍歷調用堆棧。如果未找到任何 **catch** 塊,則 CLR 向用戶顯示一條未處理的異常消息,并停止執行程序。 **try** 塊包含可能導致異常的受保護的代碼。將執行此塊,直至引發異常或其成功完成。例如,強制轉換 **null** 對象的以下嘗試會引發 [NullReferenceException](https://msdn.microsoft.com/zh-CN/library/system.nullreferenceexception.aspx) 異常: ``` object o2 = null; try { int i2 = (int)o2; // Error } ``` 盡管可以不帶參數使用 **catch** 子句來捕獲任何類型的異常,但不推薦這種用法。一般情況下,只應捕獲你知道如何從其恢復的異常。因此,應始終指定派生自 [System.Exception](https://msdn.microsoft.com/zh-CN/library/system.exception.aspx) 的對象參數,例如: ``` catch (InvalidCastException e) { } ``` 可以使用同一 try-catch 語句中的多個特定 **catch** 子句。在這種情況下,**catch** 子句的順序很重要,因為 **catch** 子句是按順序檢查的。在使用更籠統的子句之前獲取特定性更強的異常。如果捕獲塊的排序使得永不會達到之后的塊,則編譯器將產生錯誤。 篩選想要處理的異常的一種方式是使用 **catch** 參數。也可以使用謂詞表達式進一步檢查該異常以決定是否要對其進行處理。如果謂詞表達式返回 false,則繼續搜索處理程序。 ``` Catch (ArgumentException e) if (e.ParamName == “…”) { } ``` 異常篩選器要優于捕獲和重新引發(如下所述),因為篩選器將保留堆棧不受損壞。如果之后的處理程序轉儲堆棧,可以查看到異常的原始來源,而不只是重新引發它的最后一個位置。異常篩選器表達式的一個常見用途是日志記錄。可以創建一個始終返回 false 并輸出到日志的謂詞函數,而且可以在異常通過時進行記錄,無需處理并重新引發它們。 可在 **catch** 塊中使用 [throw](https://msdn.microsoft.com/zh-CN/library/1ah5wsex.aspx) 語句以重新引發已由 **catch** 語句捕獲的異常。下面的示例從 [IOException](https://msdn.microsoft.com/zh-CN/library/system.io.ioexception.aspx) 異常提取源信息,然后向父方法引發異常。 ``` 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); } ``` 當指定的條件為 true 時,你還可以重新引發異常,如以下示例所示。 ``` 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](https://msdn.microsoft.com/zh-CN/library/dszsf989.aspx)。 ### 異步方法中的異常 異步方法由 [async](https://msdn.microsoft.com/zh-CN/library/hh156513.aspx) 修飾符標記,通常包含一個或多個 await 表達式或語句。await 表達式將 [await](https://msdn.microsoft.com/zh-CN/library/hh156528.aspx) 運算符應用于 [Task](https://msdn.microsoft.com/zh-CN/library/system.threading.tasks.task.aspx) 或 [Task&lt;TResult&gt;](https://msdn.microsoft.com/zh-CN/library/dd321424.aspx)。 當控件到達異步方法中的 **await** 時,將掛起方法中的進度,直到所等待的任務完成。任務完成后,可以在方法中恢復執行。有關詳細信息,請參閱[使用 Async 和 Await 的異步編程(C# 和 Visual Basic)](https://msdn.microsoft.com/zh-CN/library/hh191443.aspx)和[異步程序中的控制流(C# 和 Visual Basic)](https://msdn.microsoft.com/zh-CN/library/hh873191.aspx)。 應用了 **await** 的完成任務可能由于返回此任務的方法中存在未處理的異常而處于錯誤狀態。等待該任務引發異常。如果取消了返回任務的異步進程,此任務最后也可能為已取消狀態。等待已取消的任務引發 **OperationCanceledException**。有關如何取消異步進程的詳細信息,請參閱 [微調異步應用程序(C# 和 Visual Basic)](https://msdn.microsoft.com/zh-CN/library/jj155761.aspx)。 若要捕獲異常,請在 **try** 塊中等待任務并在關聯的 **catch** 塊中捕獲異常。相關示例,請參見“示例”一節。 任務可能處于錯誤狀態,因為等待的異步方法中發生了多個異常。例如,任務可能是對 [Task.WhenAll](https://msdn.microsoft.com/zh-CN/library/hh160374.aspx) 調用的結果。當等待此類任務時,僅捕捉到其中一個異常,而且你無法預測將會捕獲到哪個異常。相關示例,請參見“示例”一節。 在下面的示例中,**try** 塊包含對可能引發異常的 ProcessString 方法的調用。 **catch** 子句包含只在屏幕上顯示一條消息的異常處理程序。當從 MyMethod 內部調用 **throw** 語句時,系統將查找 **catch** 語句并顯示消息 Exception caught。 ``` 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 塊,并捕獲到最先出現的最具體的異常。 若要捕獲最不具體的異常,你可以將 ProcessString 中的 throw 語句替換為以下語句:throw new Exception()。 如果將最不具體的 catch 塊置于示例中第一個,將顯示以下錯誤消息:A previous catch clause already catches all exceptions of this or a super type ('System.Exception')。 ``` 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. */ ``` 下面的示例闡釋異步方法的異常處理。若要捕獲異步任務引發的異常,將 **await** 表達式置于 **try** 塊中,并在 **catch** 塊中捕獲該異常。 將演示異常處理的示例中的 Throw New Exception 行取消注釋。 任務的 **IsFaulted** 屬性設置為 **True**,任務的 **Exception.InnerException** 屬性設置為異常,并在 **catch** 塊中捕獲該異常。 取消注釋 throw new OperationCancelledException 行以演示在取消異步進程時發生的情況。任務的 **IsCanceled** 屬性設置為 **true**,并在 **catch** 塊中捕獲異常。在某些不適用于此示例的情況下,任務的 **IsFaulted** 屬性設置為 **true** 且 **IsCanceled** 設置為 **false**。 ``` public async Task DoSomethingAsync() { Task<string> theTask = DelayAsync(); try { string result = await theTask; Debug.WriteLine("Result: " + result); } catch (Exception ex) { Debug.WriteLine("Exception Message: " + ex.Message); } Debug.WriteLine("Task IsCanceled: " + theTask.IsCanceled); Debug.WriteLine("Task IsFaulted: " + theTask.IsFaulted); if (theTask.Exception != null) { Debug.WriteLine("Task Exception Message: " + theTask.Exception.Message); Debug.WriteLine("Task Inner Exception Message: " + theTask.Exception.InnerException.Message); } } private async Task<string> DelayAsync() { await Task.Delay(100); // Uncomment each of the following lines to // demonstrate exception handling. //throw new OperationCanceledException("canceled"); //throw new Exception("Something happened."); return "Done"; } // Output when no exception is thrown in the awaited method: // Result: Done // Task IsCanceled: False // Task IsFaulted: False // Output when an Exception is thrown in the awaited method: // Exception Message: Something happened. // Task IsCanceled: False // Task IsFaulted: True // Task Exception Message: One or more errors occurred. // Task Inner Exception Message: Something happened. // Output when a OperationCanceledException or TaskCanceledException // is thrown in the awaited method: // Exception Message: canceled // Task IsCanceled: True // Task IsFaulted: False ``` 下面的示例闡釋了在多個任務可能導致多個異常的情況中的異常處理。 **try** 塊等待由 [Task.WhenAll](https://msdn.microsoft.com/zh-CN/library/hh160374.aspx) 的調用返回的任務。應用了 WhenAll 的三個任務完成后,該任務完成。 三個任務中的每一個都會導致異常。 **catch** 塊循環訪問異常,這些異常位于由 [Task.WhenAll](https://msdn.microsoft.com/zh-CN/library/hh160374.aspx) 返回的任務的 **Exception.InnerExceptions** 屬性中。 ``` public async Task DoMultipleAsync() { Task theTask1 = ExcAsync(info: "First Task"); Task theTask2 = ExcAsync(info: "Second Task"); Task theTask3 = ExcAsync(info: "Third Task"); Task allTasks = Task.WhenAll(theTask1, theTask2, theTask3); try { await allTasks; } catch (Exception ex) { Debug.WriteLine("Exception: " + ex.Message); Debug.WriteLine("Task IsFaulted: " + allTasks.IsFaulted); foreach (var inEx in allTasks.Exception.InnerExceptions) { Debug.WriteLine("Task Inner Exception: " + inEx.Message); } } } private async Task ExcAsync(string info) { await Task.Delay(100); throw new Exception("Error-" + info); } // Output: // Exception: Error-First Task // Task IsFaulted: True // Task Inner Exception: Error-First Task // Task Inner Exception: Error-Second Task // Task Inner Exception: Error-Third Task ``` ## C# 語言規范 有關詳細信息,請參閱 [C# 語言規范](https://msdn.microsoft.com/zh-CN/library/ms228593.aspx)。該語言規范是 C# 語法和用法的權威資料。 ## 請參閱 [C# 參考](https://msdn.microsoft.com/zh-CN/library/618ayhy6.aspx) [C# 編程指南](https://msdn.microsoft.com/zh-CN/library/67ef8sbd.aspx) [C# 關鍵字](https://msdn.microsoft.com/zh-CN/library/x53a06bb.aspx) [try、throw 和 catch 語句 (C++)](https://msdn.microsoft.com/zh-CN/library/6dekhbbc.aspx) [異常處理語句(C# 參考)](https://msdn.microsoft.com/zh-CN/library/s7fekhdy.aspx) [throw(C# 參考)](https://msdn.microsoft.com/zh-CN/library/1ah5wsex.aspx) [try-finally(C# 參考)](https://msdn.microsoft.com/zh-CN/library/zwc8s4fz.aspx) [如何:顯式引發異常](https://msdn.microsoft.com/zh-CN/library/xhcbs8fz.aspx)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看