问题
Suppose the following example. There are classes A-C derived from std::exception:
#include <exception>
#include <string>
#include <iostream>
class A : public std::exception {
std::string a_text;
public:
A(const std::string & a_text_) : a_text(a_text_) {}
virtual ~A() throw() { }
};
class B : public A {
const std::string b_text;
public:
B(const std::string &a_text_, const std::string & b_text_) : A(a_text_), b_text(b_text_) {}
virtual ~B() throw() {}
};
template <typename T>
class C : public B {
T x;
public:
C(const std::string & a_text_, const std::string & b_text_, const T x_) :
B (b_text_, a_text_), x(x_) { }
virtual ~C() throw() {};
};
So far I have been convinced that generalizing pattern catches the exception of the derived class in multiple blocks.
int main() {
try {
throw C<double>("a", "b", 10);
}
catch (C<double> &c1) {
std::cout << " C";
}
catch (B &b1) {
std::cout << " B";
}
}
Unfortunately, the second block referring to B is skipped. Where is the problem? Thanks for your help.
回答1:
Only the first catch block that matches is going to execute. You can re-throw the existing exception with the "throw;" statement but I am not sure if that will continue the search at the next catch block or only in a outer try-catch.
来源:https://stackoverflow.com/questions/47731587/c-catch-user-defined-exceptions-in-multiple-blocks