C ++,在多个块中捕获用户定义的异常

时间:2017-12-09 18:06:23

标签: c++ exception-handling user-defined-types

假设以下示例。有来自std :: exception的类A-C:

#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() {};
};

到目前为止,我一直相信泛化模式会捕获多个块中派生类的异常。

int main() {
 try {
    throw C<double>("a", "b", 10);
 }

 catch (C<double> &c1) {
    std::cout << " C";
 }

 catch (B &b1) {
    std::cout << " B";
 }
}

不幸的是,跳过了引用B的第二个块。问题出在哪儿?谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

只有匹配的第一个catch块才会执行。您可以使用&#34; throw;&#34;重新抛出现有异常。声明,但我不确定这是否会继续搜索下一个catch块或仅在外部try-catch中。