阅读量:101
在 Ubuntu 中使用 C++ 进行异常处理,主要依赖于 C++ 的异常处理机制,即 try、catch 和 throw 关键字。下面是一个简单的示例,展示了如何在 C++ 中使用异常处理:
#include
#include // 包含标准异常类
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 class="hljs-built_in">catch (const std::invalid_argument& e) {
std::cerr << "Caught an exception: " << e class="hljs-built_in">what() << std class="hljs-comment">// 捕获并处理异常
} catch (...) {
std::cerr << "Caught an unknown exception." << std class="hljs-keyword">return 0;
}
代码解析:
-
抛出异常:
- 在
divide函数中,如果分母为零,我们使用throw关键字抛出一个std::invalid_argument异常。这是一个标准库提供的异常类,用于表示参数错误。
- 在
-
异常处理:
- 在
main函数中,我们使用try块包围可能抛出异常的代码。 - 如果
divide函数抛出异常,控制流会立即跳转到相应的catch块。 - 我们捕获了
std::invalid_argument类型的异常,并打印出异常信息。 - 另外一个
catch (...)块用于捕获所有其他类型的异常,确保程序不会因为未处理的异常而崩溃。
- 在
-
编译和运行:
- 使用 g++ 编译这个程序,可以使用以下命令:
g++ -o exception_example exception_example.cpp - 然后运行生成的可执行文件:
./exception_example
- 使用 g++ 编译这个程序,可以使用以下命令:
异常处理是 C++ 中管理错误和异常情况的重要机制,它可以帮助你编写更健壮和可维护的代码。