include <iostream> using namespace std; class A{}; class B:public A{}; void func(void){ //throw B();可以抛出A也可以抛出B throw A(); } int main(void) { try{ func(); } catch(B& ex){ cout << "catch:B" << endl;//如果这里catch (A& ex)和catch(B& ex) //互换,则结果都是catch:A return -1; } catch(A& ex){ cout << "catch:A" << endl; return -1; } return 0; }
catch子句会根据异常的类型自上而下顺序匹配,而不是最优匹配
catch子句中使用引用接受异常对象,避免拷贝构造的性能开销,同时可以减少浅拷贝的风险
本文出自 “12208412” 博客,请务必保留此出处http://12218412.blog.51cto.com/12208412/1869196
原文地址:http://12218412.blog.51cto.com/12208412/1869196