【问题标题】:How to emphasize that function may throw?如何强调该功能可能会抛出?
【发布时间】:2020-01-04 03:00:39
【问题描述】:

考虑以下函数:

void checkPlayerCounter() {
    if (playerCounter != consts::numberOfPlayers) {
        throw std::runtime_error("Detected " + std::to_string(playerCounter)
          + " player instead of " + std::to_string(consts::numberOfPlayers));
    }
}

函数可能会抛出,为了便于阅读,我想在头文件内的函数声明中强调这一点。我怎样才能做到这一点?

我正在寻找类似的东西:

void checkPlayerCounter() may throw;

【问题讨论】:

    标签: c++ exception throw


    【解决方案1】:

    您可以明确使用noexcept(false)。就在你建议的地方:

    void checkPlayerCounter() noexcept(false);
    

    不幸的是,没有办法避免noexcept 的双重否定。另一种选择是评论:

    void checkPlayerCounter(); // may throw
    

    也就是说,阅读声明的人应该始终假设函数可能抛出异常,除非另有说明。

    【讨论】:

    • 可以使用宏:#define MAY_THROW noexcept(false)
    • @Brian 虽然采用这种方法,但无法避免使用宏 :)
    【解决方案2】:
    /**
     * @throws std::runtime_error
     */
    void checkPlayerCounter();
    

    【讨论】:

      猜你喜欢
      • 2021-03-12
      • 1970-01-01
      • 2015-05-25
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      • 2018-11-15
      • 2018-12-26
      相关资源
      最近更新 更多