C++异常机制的执行顺序。
在构造函数内抛出异常
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/* * ExceptClass.h * * Created on: 2018年1月2日 * Author: jacket */ #ifndef EXCEPTCLASS_H_ #define EXCEPTCLASS_H_ #include <iostream> using std::cout; using std::endl; class ExceptClass { public: ExceptClass(){ cout<<"ExcepClass"<<endl; throw int(1); } void start(){ } virtual ~ExceptClass() { cout<<"~ExcepClass"<<endl; } }; #endif /* EXCEPTCLASS_H_ */
如果外部没有try catch,输出
ExcepClass terminate called after throwing an instance of 'int'
如果外部try catch
ExcepClass
Catch
在start()内抛出异常
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/* * ExceptClass.h * * Created on: 2018年1月2日 * Author: jacket */ #ifndef EXCEPTCLASS_H_ #define EXCEPTCLASS_H_ #include <iostream> using std::cout; using std::endl; class ExceptClass { public: ExceptClass(){ cout<<"ExcepClass"<<endl; } void start(){ throw int(1); } virtual ~ExceptClass() { cout<<"~ExcepClass"<<endl; } }; #endif /* EXCEPTCLASS_H_ */
如果外部没有try catch
ExcepClass terminate called after throwing an instance of 'int'
如果外部try catch
ExcepClass ~ExcepClass Catch
所以,如果在构造函数内抛出异常,析构函数将不被调用。如果在其他函数内抛出异常,析构函数会被调用。
而且如果外部没有try catch不会调用析构函数,说明C++抛出异常后是先回退(好像是栈有关的回退),检测到异常会被捕捉才进入析构函数。
刚试了下有try catch但捕捉类型改为float,也不会进入析构函数。
Exception机制还有有多注意点。在学习过程中参考了不少文章。
C++异常处理之abort()、异常机制、exception 类(从这里开始了解到)
C++异常(exception)第一篇--综合讲解(这个最有深度,很多注意点)
知乎上看到一些人评价c++的exception很难用,想问一下大家写c++时怎么处理错误?(很多大神透露的经验,还要继续吃透)
深入理解C++异常(好像有深入的讲解,但我没细看)
C++自定义异常处理(其实没啥用,但是一开始不懂异常机制是什么,还以为要有啥规范)
C++ 标准库中的异常(在linux下试了下logic_error,segfault,确定是在构造logic_error时报错,没找原因直接继承exception自定义了)