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

C++, catch user-defined exceptions in multiple blocks

本文关键字:用户 定义 异常      更新时间:2023-10-16

假设以下示例。有从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的块被跳过。哪里有问题?感谢您的帮助。

仅匹配的第一个捕获块才能执行。您可以用"投掷"重新验证现有的异常;语句,但我不确定这是否会继续在下一个捕获块或仅在外部试用器中继续进行搜索。