C++,在多个块中捕获用户定义的异常
C++, catch user-defined exceptions in multiple blocks
假设有以下例子。有 classes A-C 派生自 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() {};
};
到目前为止,我确信泛化模式可以捕获多个块中派生的 class 的异常。
int main() {
try {
throw C<double>("a", "b", 10);
}
catch (C<double> &c1) {
std::cout << " C";
}
catch (B &b1) {
std::cout << " B";
}
}
不幸的是,跳过了引用 B 的第二个块。问题出在哪里?感谢您的帮助。
只有第一个匹配的 catch 块才会执行。您可以使用 "throw;" 语句重新抛出现有异常,但我不确定这是否会在下一个 catch 块或仅在外部 try-catch 中继续搜索。
假设有以下例子。有 classes A-C 派生自 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() {};
};
到目前为止,我确信泛化模式可以捕获多个块中派生的 class 的异常。
int main() {
try {
throw C<double>("a", "b", 10);
}
catch (C<double> &c1) {
std::cout << " C";
}
catch (B &b1) {
std::cout << " B";
}
}
不幸的是,跳过了引用 B 的第二个块。问题出在哪里?感谢您的帮助。
只有第一个匹配的 catch 块才会执行。您可以使用 "throw;" 语句重新抛出现有异常,但我不确定这是否会在下一个 catch 块或仅在外部 try-catch 中继续搜索。