在 c++++ 中,異常通過 try-catch 語句處理:try 塊中代碼可能拋出異常。catch 塊捕獲標準異常或自定義異常。noexcept 關(guān)鍵字聲明函數(shù)不會拋出異常,以進行優(yōu)化。
C++ 函數(shù)中如何處理異常?
在 C++ 中,異常通過 try-catch 語句處理,包括三個主要部分:
try {
// 代碼塊,可能拋出異常
}
catch (const std::exception& e) {
// 捕獲標準異常
}
catch (const MyCustomException& e) {
// 捕獲自定義異常
}
登錄后復制
實戰(zhàn)案例:
假設(shè)我們有一個函數(shù) divide,它計算兩個數(shù)的商,但當分母為 0 時拋出異常:
int divide(int num, int denom) {
try {
if (denom == 0) {
throw std::runtime_error("除數(shù)不能為 0");
}
return num / denom;
}
catch (const std::exception& e) {
std::cout << "錯誤: " << e.what() << std::endl;
}
}
登錄后復制
在主函數(shù)中,我們可以調(diào)用 divide 函數(shù)并捕獲異常:
int main() {
try {
int dividend = 10;
int divisor = 0;
int result = divide(dividend, divisor);
std::cout << dividend << " / " << divisor << " = " << result << std::endl;
}
catch (const std::runtime_error& e) {
std::cout << e.what() << std::endl;
}
}
登錄后復制
輸出:
錯誤: 除數(shù)不能為 0
登錄后復制
注意:
函數(shù)中也可以拋出自定義異常,通過創(chuàng)建自定義異常類并繼承 std::exception。
使用 noexcept 關(guān)鍵字聲明函數(shù)不會拋出異常,以進行優(yōu)化。






