阅读量:97
在C++程序中,异常处理是通过使用try、catch和throw关键字来实现的。当程序遇到错误或异常情况时,可以使用这些关键字来捕获和处理异常,从而避免程序崩溃。
以下是一个简单的C++异常处理示例:
#include
#include
int main() {
int a = 10;
int b = 0;
try {
if (b == 0) {
throw std::runtime_error("除数不能为0");
}
int result = a / b;
std::cout << "结果是: " << result class="hljs-built_in">catch (const std::runtime_error& e) {
std::cerr << "捕获到异常: " << e class="hljs-built_in">what() << std class="hljs-keyword">return 0;
}
在这个示例中,我们尝试执行一个除法操作。如果除数为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块中处理它们。