我有两个函数 a()
和 b()
,它们有自己的异常类(连续 a_exc
和 b_exc
) 继承自 std::logic_error
。
void a() { (...) throw a_exc(some_val) }
void b() { (...) throw b_exc(some_val) }
class a_exc : public std::logic_error
{
private:
int foo;
public:
a_exc(int val, const std::string& what_msg="Msg.")
: std::logic_error(what_msg), foo(val) {}
void show() { //show foo }
}
class b_exc : public std::logic_error
{
private:
std::string bar;
public:
a_exc(std::string val, const std::string& what_msg="Msg.")
: std::logic_error(what_msg), bar(val) {}
void show() { //show bar }
}
假设我有以下部分代码:
try {
a();
b();
}
catch (const std::logic_error& e)
{
e.what();
// e.show();
}
catch (const std::logic_error& e)
捕获 a_exc
和 b_exc
。当然这个 block 不能使用e.show()
,因为捕获的obj是std::logic_error
。
这是我的问题。我想知道当捕获的异常是 a_exc
或 时,是否有机会在
。我知道,如果我为 std::logic_error
catch block 中调用 show()
方法b_exca_exc
和 b_exc
创建单独的 catch block ,调用 show()
是可能的,但我想调用此方法使用只有一个 catch block 。可能吗?
最佳答案
你可以,前提是 show()
是一个 const
成员函数:
catch (const std::logic_error& e)
{
e.what();
if(const a_exc* a = dynamic_cast<const a_exc*>(&e))
a->show();
else if(const b_exc* b = dynamic_cast<const b_exc*>(&e))
b->show();
}
查看Live on Coliru .不过,在您的 catch
异常处理程序中调用可能会throw
的其他函数通常不是一个好主意。
关于c++ - 从其基类捕获的自己的异常类调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39583234/