-
try
(C++關鍵字)
鎖定
- 中文名
- 異常處理組合
- 外文名
- try
- 類 型
- 關鍵字
- 語 種
- C++
try功能
若要處理可能引發的異常,請緊接在try塊之後實現一個或多個catch塊。 每個catch塊指定它可以處理的異常類型。
try代碼示例
本例顯示了一個try塊及其處理程序。假設GetNetworkResource()通過網絡連接獲取數據,並且這兩種異常類型是從std::exception派生的用户定義類。請注意,這些異常是由catch語句中的const引用捕獲的。我們建議您按值拋出異常,並按常量引用捕獲它們。
[2]
MyData md; try { // Code that could throw an exception md = GetNetworkResource(); } catch (const networkIOException& e) { // Code that executes when an exception of type // networkIOException is thrown in the try block // ... // Log error message in the exception object cerr << e.what(); } catch (const myDataFormatException& e) { // Code that handles another exception type // ... cerr << e.what(); } // The following syntax shows a throw expression MyData GetNetworkResource() { // ... if (IOSuccess == false) throw networkIOException("Unable to connect"); // ... if (readError) throw myDataFormatException("Format error"); // ... }
- 參考資料
-
- 1. 黃寶貴,黃萬麗,馬春梅,禹繼國,趙景秀,閆超.C++面向對象程序設計.北京:清華大學出版社,2020-04-09:315-316
- 2. try, throw, and catch Statements (C++) | Microsoft Docs .Microsoft Docs[引用日期2022-05-11]