C++的異常處理是一種用于處理運行時錯誤的機制
try {
// 可能引發異常的代碼
}
try {
// 可能引發異常的代碼
} catch (ExceptionType1 e) {
// 處理ExceptionType1類型的異常
} catch (ExceptionType2 e) {
// 處理ExceptionType2類型的異常
}
if (error_condition) {
throw ExceptionType(error_message);
}
#include <exception>
class MyException : public std::exception {
public:
const char* what() const noexcept override {
return "My custom exception occurred";
}
};
下面是一個簡單的C++異常處理示例:
#include <iostream>
#include <stdexcept>
int main() {
try {
int denominator = 0;
if (denominator == 0) {
throw std::runtime_error("Division by zero");
}
int result = 10 / denominator;
std::cout << "Result: " << result << std::endl;
} catch (const std::runtime_error& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
在這個示例中,我們嘗試執行一個除以零的操作,這會引發一個運行時錯誤。我們使用throw關鍵字拋出一個std::runtime_error異常,并在catch塊中捕獲并處理它。