在C++中,异常处理是通过使用try
、catch
和throw
关键字来实现的。以下是一个简单的示例,展示了如何在C++中使用异常处理:
#include <iostream>
#include <stdexcept>
int main() {
int num1 = 10;
int num2 = 0;
int result;
try {
if (num2 == 0) {
throw std::runtime_error("除数不能为0");
}
result = num1 / num2;
std::cout << "结果是: " << result << std::endl;
} catch (const std::runtime_error& e) {
std::cerr << "捕获到异常: " << e.what() << std::endl;
}
return 0;
}
在这个示例中,我们尝试将num1
除以num2
。如果num2
为0,我们抛出一个std::runtime_error
异常,并附带一条错误消息。try
块中的代码尝试执行除法操作,如果抛出异常,它将被catch
块捕获。catch
块捕获一个std::runtime_error
类型的引用,并输出异常消息。
要在Ubuntu上编译和运行此示例,请按照以下步骤操作:
exception_handling.cpp
的文件中。exception_handling.cpp
文件的目录。g++ -o exception_handling exception_handling.cpp
./exception_handling
如果一切正常,您将看到以下输出:
捕获到异常: 除数不能为0
这就是在C++中使用异常处理的基本方法。您可以根据需要使用不同类型的异常,并在catch
块中处理它们。