【问题标题】:Base class throws exception. How to propagate?基类抛出异常。如何传播?
【发布时间】:2020-11-15 13:48:37
【问题描述】:
class base {
  public:
    base() : value(int()) {
      throw true;
    }
  private:
    int value;
};

class derived : public base {
  public:
    derived() : base() {  // base class constructor called, `value` to be initialized
      // I want this to propagate (rethrow) base class exception... how do I do it?
    }
};

int main(){
  try {
    derived a;
  }
  catch(bool){
    // Base class exception to be caught
  }

}

在上面的例子中已经说过了。如何传播(重新抛出)基类异常?

我试试这个可憎的:

class base {
  public:
    base() : value(int()) {
      throw true;
    }
  private:
    int value;
};

class derived : public base {
  public:
    derived() : try { base() } catch(bool) {throw;} {
      // ...
    }
};

int main(){
  try {
    derived a;
  }
  catch(bool){
    // Base class exception to be caught
  }

}

不编译,给出语法错误。非常期待。解决办法是什么?

不要继续阅读。需要更多字符。输入更多字符。

【问题讨论】:

  • 好吧,你说我必须catch。我如何以这种方式捕捉它们的异常:derived() : try { base() } catch(bool){throw;} {}。我认为这是一个非常聪明的主意,尽管我的兄弟们称我为白痴
  • 你是个很聪明的人。我尝试trycatch,因为它写在上面的评论中。 Tho' me homies callin' me bit粗。我的代码有什么问题?
  • 不编译,伙计
  • 使用这个:derived() try : base() { } catch(bool) { throw; } ...评论中的语法排列错误。
  • @user3600124 例如见Function-try-block。另外请注意,在构造函数周围的 catch 块内,您不应引用 basederived 中的任何内容,因为此时没有正确构造任何对象。

标签: c++ exception try-catch


【解决方案1】:

您问题中的代码已经完全符合您的要求 (see demo here)。异常将调用堆栈回退到最近的处理异常类型的 catch 块。

由于derived::derived() 构造函数没有捕获异常,它会自动传播给调用者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2013-05-24
    • 1970-01-01
    相关资源
    最近更新 更多