#include <iostream> usingnamespace std; class X ...{ public: class Trouble ...{}; class Small : public Trouble ...{}; class Big : public Trouble ...{}; void f() ...{ throw Big(); } }; int main() ...{ X x; try...{ x.f(); }catch(X::Trouble&) ...{ cout <<"caught Trouble"<< endl; // Hidden by previous handler: }catch(X::Small&) ...{ cout <<"caught Small Trouble"<< endl; }catch(X::Big&) ...{ cout <<"caught Big Trouble"<< endl; }catch(...) ...{ cout <<"an exception was thrown"<< endl; } }/**////:~
结果是catch基类也能捕获子类的异常。
再rethrow一次
#include <iostream> usingnamespace std; class X ...{ public: class Trouble ...{}; class Small : public Trouble ...{}; class Big : public Trouble ...{}; void f() ...{ throw Big(); } }; int main() ...{ X x; try ...{ try...{ x.f(); }catch(X::Trouble&) ...{ cout <<"caught Trouble"<< endl; throw; }catch(X::Small&) ...{ cout <<"caught Small Trouble"<< endl; }catch(X::Big&) ...{ cout <<"caught Big Trouble"<< endl; } }catch(...) ...{ cout<<"rethrow caught"<<endl; } }/**////:~
可以跑,但是有警告,warning: exception of type `X::Small' will be caught。。。。。。。不晓得原因。