数结束程序;
2,调用 set_unexpected() 设置自定义的异常函数:
1,参数类型为 void(*)();
2,返回值为默认的 unexpected() 函数入口地址;
10,自定义 unexpected() 函数编程实验:
1 #include <iostream>
2 #include <cstdlib>
3 #include <exception>
4
5 using namespace std;
6
7 void my_unexpected()
8 {
9 cout << "void my_unexpected()" << endl;
10 // exit(1); // 退出;
11 throw 1;
12 }
13
14 void func() throw(int)
15 {
16 cout << "func()";
17 cout << endl;
18
19 throw 'c';
20 }
21
22 int main()
23 {
24 set_unexpected(my_unexpected);
25
26 try
27 {
28 func();
29 }
30 catch(int)
31 {
32 cout << "catch(int)";
33 cout << endl;
34 }
35 catch(char)
36 {
37 cout << "catch(char)";
38 cout << endl;
39 }
40
41 return 0;
42 }
1,exit(1) 结果:
1,g++ 编译器:
func()
void my_unexpected()
2,BCC 编译器:
func()
void my_unexpected()
3,VC 2010 编译器:
func()
catch(char) // 未有遵循标准 C++ 规范;
2,throw 1 结果:
1,g++ 编译器:
func()
void my_unexpected()
catch(int) //与触发函数 func() 的异常规格符合,于是程序恢复执行;
2,BCC 编译器:
func()
void my_unexpected()
catch(int)
3,VC 2010 编译器:
func()
catch(char) // 未有遵循标准 C++ 规范,直接捕获,然后处理;
3,如果以后项目开发,会使用函数异常说明这个技术点,最好在项目开发前写一些小程序测试下当前使用的 C++ 编译器有没有很好的遵循 C++ 的规范;
11,小结:
1,C++ 中的函数可以声明异常规则说明;
2,异常规格说明可以看作接口的一部分;
3,函数抛出的异常不在规格说明中,unexpected() 被调用;
4,unexpected() 中能够再次抛出异常;
1,异常能够匹配,恢复程序的执行;
2,否则,调用 terminate() 结束程序;
3,un_expected() 函数是正确处理异常的最后机会,如果没有抓住,terminate() 函数会被调用,当前程序以异常告终;