在 Ubuntu 下使用 C++ 進行異常處理,你需要遵循以下步驟:
<stdexcept>
頭文件,它包含了標準異常類的定義。#include <stdexcept>
throw
關鍵字拋出一個異常。你可以使用標準異常類(如 std::runtime_error
、std::invalid_argument
等),也可以自定義異常類。if (error_condition) {
throw std::runtime_error("An error occurred");
}
try
和 catch
塊來捕獲和處理異常。try
塊包含可能拋出異常的代碼,catch
塊包含處理異常的代碼。try {
// Code that may throw an exception
} catch (const std::exception& e) {
// Code to handle the exception
std::cerr << "Exception caught: " << e.what() << std::endl;
}
下面是一個簡單的示例,演示了如何在 Ubuntu 下使用 C++ 進行異常處理:
#include <iostream>
#include <stdexcept>
int main() {
int divisor;
std::cout << "Enter a number to divide by: ";
std::cin >> divisor;
try {
if (divisor == 0) {
throw std::invalid_argument("Division by zero is not allowed");
}
int result = 100 / divisor;
std::cout << "Result: " << result << std::endl;
} catch (const std::invalid_argument& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
在這個示例中,我們嘗試將 100 除以用戶輸入的數字。如果用戶輸入 0,我們將拋出一個 std::invalid_argument
異常,并在 catch
塊中捕獲和處理它。