【问题标题】:C++, catch user-defined exceptions in multiple blocksC++,在多个块中捕获用户定义的异常
【发布时间】:2021-03-18 19:34:51
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • @SornelHaetir:如果存在,它将在外部 catch 块中继续。
    猜你喜欢
    • 2011-01-31
    • 1970-01-01
    • 2011-02-24
    • 2011-09-22
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多