异常
1. 错误处理
如果出现本身不能处理的错误,那么发生错误的代码和处理错误的代码不在同一处。常用的错误处理的方式
- 终止程序
- 返回一个表示错误的值
- 默默的返回
- 设置全局出错变量
- 抛出异常
2. 异常处理方式
3. 处理多种异常
1 class Overflow {
2 };
3
4 class Underflow{
5 };
6
7 class Stack {
8 int size;
9 int capacity;
10 public:
11 void push(int x) {
12 if(size >= capacity) {
13 Overflow e;
14 throw e;
15 }
16 }
17 void pop() {
18 if(size <=0)
19 throw Underflow();
20 }
21 };
22
23 int main() {
24 Stack s;
25 try {
26 s.pop();
27 s.push(10);
28 }
29 catch(Overflow e) {
30 cout << "Overflow" << endl;
31 }
32 catch(Underflow e) {
33 cout << "Underflow" << endl;
34 }
35 }
给异常添加派生结构:
1 class StackError {
2 };
3
4 class Overflow : public StackError {
5 };
6
7 class Underflow : public StackError{
8 };
9
10 class Stack {
11 int size;
12 int capacity;
13 public:
14 void push(int x) {
15 if(size >= capacity) {
16 Overflow e;
17 throw e;
18 }
19 }
20 void pop() {
21 if(size <=0)
22 throw Underflow();
23 }
24 };
25
26 int main() {
27 Stack s;
28 try {
29 s.pop();
30 s.push(10);
31 }
32 catch(Overflow e) {
33 cout << "Overflow" << endl;
34 }
35 catch(Underflow e) {
36 cout << "Underflow" << endl;
37 }
38 catch(StackError e) {
39 cout << "StackError" << endl;
40 }
41 }
捕捉所有未知异常
1 class StackError {
2 };
3
4 class Overflow : public StackError {
5 };
6
7 class Underflow : public StackError{
8 };
9
10 class Stack {
11 int size;
12 int capacity;
13 public:
14 void push(int x) {
15 if(size >= capacity) {
16 throw "Error";
17 }
18 }
19 void pop() {
20 if(size <=0)
21 throw Underflow();
22 }
23 };
24
25 int main() {
26 Stack s;
27 try {
28 s.pop();
29 s.push(10);
30 }
31 catch(Overflow e) {
32 cout << "Overflow" << endl;
33 }
34 catch(Underflow e) {
35 cout << "Underflow" << endl;
36 }
37 catch(StackError e) {
38 cout << "StackError" << endl;
39 }
40 catch(...) {
41 cout << "Unknown Error" << endl;
42 }
43 }
4. 标准异常体系
在头文件<exception>中定义了基类exception。
dynamic_cast转换引用出错:bad_cast
new分配内存出错:bad_alloc
at访问成员:out_of_range