文章目录
c++异常处理机制详解
C++的异常处理机制通过try, catch和throw关键字来实现。它允许程序在运行时捕获和处理错误,而不是直接终止程序。下面是对C++异常处理机制的详细解释:
基本原理
1. try 块
try块用于包围可能抛出异常的代码。它的语法如下:
try {
// 可能抛出异常的代码
}
2. throw 语句
throw语句用于抛出一个异常。它可以抛出任何类型的对象,但通常抛出的是标准异常类或自定义异常类的对象。语法如下:
throw 异常对象;
3. catch 块
catch块用于捕获和处理异常。它紧跟在try块之后,可以有多个catch块来处理不同类型的异常。语法如下:
catch (异常类型& 异常对象) {
// 处理异常的代码
}
示例代码
下面是一个完整的示例,展示了如何使用try, catch和throw来进行异常处理:
#include <iostream>
#include <stdexcept>
void mightGoWrong() {
bool error1 = true;
bool error2 = false;
if (error1) {
throw std::runtime_error("Something went wrong");
}
if (error2) {
throw std::exception();
}
}
int main() {
try {
mightGoWrong();
} catch (const std::runtime_error& e) {
std::cerr << "Runtime error: " << e.what() << std::endl;
} catch (const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
std::cout << "Program continues..." << std::endl;