在 Ubuntu 中使用 C++ 进行异常处理,主要依赖于 C++ 的异常处理机制,即 try
、catch
和 throw
关键字。下面是一个简单的示例,展示了如何在 C++ 中使用异常处理:
#include <iostream>
#include <stdexcept> // 包含标准异常类
int divide(int numerator, int denominator) {
if (denominator == 0) {
throw std::invalid_argument("Denominator cannot be zero."); // 抛出异常
}
return numerator / denominator;
}
int main() {
int num1 = 10;
int num2 = 0;
try {
int result = divide(num1, num2); // 调用可能抛出异常的函数
std::cout << "Result: " << result << std::endl;
} catch (const std::invalid_argument& e) {
std::cerr << "Caught an exception: " << e.what() << std::endl; // 捕获并处理异常
} catch (...) {
std::cerr << "Caught an unknown exception." << std::endl;
}
return 0;
}
抛出异常:
divide
函数中,如果分母为零,我们使用 throw
关键字抛出一个 std::invalid_argument
异常。这是一个标准库提供的异常类,用于表示参数错误。异常处理:
main
函数中,我们使用 try
块包围可能抛出异常的代码。divide
函数抛出异常,控制流会立即跳转到相应的 catch
块。std::invalid_argument
类型的异常,并打印出异常信息。catch (...)
块用于捕获所有其他类型的异常,确保程序不会因为未处理的异常而崩溃。编译和运行:
g++ -o exception_example exception_example.cpp
./exception_example
异常处理是 C++ 中管理错误和异常情况的重要机制,它可以帮助你编写更健壮和可维护的代码。