在C++中,異常處理是通過使用 try、catch 和 throw 語句來實現的。以下是一個簡單的示例,展示了如何在C++方法中進行異常處理:
#include <iostream>
#include <stdexcept>
int divide(int a, int b) {
if (b == 0) {
throw std::runtime_error("Division by zero is not allowed.");
}
return a / b;
}
int main() {
try {
int result = divide(10, 0);
std::cout << "The result is: " << result << std::endl;
} catch (const std::runtime_error& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
在這個示例中,我們定義了一個名為 divide
的方法,該方法接受兩個整數參數 a
和 b
。在方法內部,我們檢查除數 b
是否為零。如果是零,我們拋出一個 std::runtime_error
異常,并提供一個描述性錯誤消息。
在 main
方法中,我們使用 try
語句調用 divide
方法。如果 divide
方法拋出異常,程序將立即跳轉到與該異常類型匹配的 catch
塊。在這個例子中,我們捕獲了 std::runtime_error
異常,并在 catch
塊中打印錯誤消息。
注意,為了避免程序意外終止,建議在可能拋出異常的代碼周圍使用 try-catch
語句。這樣可以確保程序在遇到錯誤時能夠優雅地處理異常情況。