在C++中,異常處理是通過使用try
、catch
和throw
關鍵字來實現的。以下是一個簡單的示例,展示了如何在C++中使用異常處理:
#include <iostream>
#include <stdexcept>
int main() {
int num1 = 10;
int num2 = 0;
int result;
try {
if (num2 == 0) {
throw std::runtime_error("除數不能為0");
}
result = num1 / num2;
std::cout << "結果是: " << result << std::endl;
} catch (const std::runtime_error& e) {
std::cerr << "捕獲到異常: " << e.what() << std::endl;
}
return 0;
}
在這個示例中,我們嘗試將num1
除以num2
。如果num2
為0,我們拋出一個std::runtime_error
異常,并附帶一條錯誤消息。try
塊中的代碼嘗試執行除法操作,如果拋出異常,它將被catch
塊捕獲。catch
塊捕獲一個std::runtime_error
類型的引用,并輸出異常消息。
要在Ubuntu上編譯和運行此示例,請按照以下步驟操作:
exception_handling.cpp
的文件中。exception_handling.cpp
文件的目錄。g++ -o exception_handling exception_handling.cpp
./exception_handling
如果一切正常,您將看到以下輸出:
捕獲到異常: 除數不能為0
這就是在C++中使用異常處理的基本方法。您可以根據需要使用不同類型的異常,并在catch
塊中處理它們。