c++ - 从其基类捕获的自己的异常类调用方法

标签 c++

我有两个函数 a()b(),它们有自己的异常类(连续 a_excb_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_excb_exc。当然这个 block 不能使用e.show(),因为捕获的obj是std::logic_error

这是我的问题。我想知道当捕获的异常是 a_exc 时,是否有机会在 std::logic_error catch block 中调用 show() 方法b_exc。我知道,如果我为 a_excb_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/

相关文章:

c++ - 如何编程以防止 Windows "Not Responding"对话框

c++ - int x = 'fooo' 是编译器扩展吗?

c++ - 找不到标识符。

c# - Google 带注释的时间线组件的桌面版?

C++ 错误 : base function is protected

c++ - QT : webkit webkitwidgets creating a click package on Ubuntu 中的未知模块

c++ - 声明 "intrinsics"只是对编译器的建议是否正确?

c++ - 按子字符串对字符串 vector 进行排序?

c++ - token 前的预期不合格 ID

c++ - gdb 在单例的静态方法中没有显示 '' 这个''?