C++ 中的异常处理机制如何工作?
在 C++ 中,异常处理是处理运行时错误的过程。异常是在 C++ 中运行时抛出的事件。所有异常都派生自 std::exception 类。它是一个可以处理的运行时错误。如果我们不处理异常,它会打印异常消息并终止程序。
异常在 C++ 标准中定义为 `

C++ 中常见的异常类:
| 序号 | 异常及描述 |
|---|---|
| 1 | std::exception 这是一个异常,也是所有标准 C++ 异常的父类。 |
| 2 | std::bad_cast 由 dynamic_cast 抛出的异常。 |
| 3 | std::bad_exception 此异常用于处理 C++ 程序中的意外异常。 |
| 4 | std::bad_alloc 通常由 new 抛出。 |
| 5 | std::logic_error 此异常可以通过阅读代码来检测。 |
| 6 | std::runtime_error 此异常无法通过阅读代码来检测。 |
| 7 | std::bad_typeid 由 typeid 抛出的异常。 |
关键词
异常处理中有 3 个关键词:try、catch 和 throw。
Try/Catch 块
在 C++ 中,异常处理使用 try/catch 语句执行。可能发生异常的代码放在 Try 块中。Catch 块用于处理异常。
示例代码
#include <iostream>
using namespace std;
class Sample1 {
public:
Sample1() {
cout << "Construct an Object of sample1" << endl;
}
~Sample1() {
cout << "Destruct an Object of sample1" << endl;
}
};
class Sample2 {
public:
Sample2() {
int i=7;
cout << "Construct an Object of sample2" << endl;
throw i;
}
~Sample2() {
cout << "Destruct an Object of sample2" << endl;
}
};
int main() {
try {
Sample1 s1;
Sample2 s2;
} catch(int i) {
cout << "Caught " << i << endl;
}
}输出
Construct an Object of sample1 Construct an Object of sample2 Destruct an Object of sample1 Caught 7
用户自定义异常
我们可以通过继承和重写异常类的功能来定义我们自己的异常。
示例代码
#include <iostream>
#include <exception> using namespace std;
struct DivideByZero : public exception {
const char * what () const throw () {
return "My Exception";
}
};
int main() {
try {
throw DivideByZero();
} catch(DivideByZero& e) {
cout << "Exception caught" << endl; cout << e.what() << endl;
} catch(exception& e) {
}
}输出
Exception caught My Exception what() = A public method provided by exception class and it has been overridden by all the child exception classes. It returns the cause of an exception.
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP