C ++,在多个块中捕获用户定义的异常 [英] C++, catch user-defined exceptions in multiple blocks
问题描述
假设以下示例.从std :: exception派生的类A-C:
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";
}
}
不幸的是,第二个引用B的块被跳过了.问题出在哪儿?感谢您的帮助.
Unfortunately, the second block referring to B is skipped. Where is the problem? Thanks for your help.
推荐答案
只有匹配的第一个catch块将要执行.您可以使用"throw;"将现有异常重新抛出.语句,但我不确定是否会在下一个catch块或仅在外部try-catch中继续搜索.
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.
这篇关于C ++,在多个块中捕获用户定义的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!