在 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
块中捕获和处理它。