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

若如初见. 提交于 2021-02-05 11:10:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!