首页 > 解决方案 > 如何强调该功能可能会抛出?

问题描述

考虑以下函数:

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++exceptionthrow

解决方案


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

void checkPlayerCounter() noexcept(false);

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

void checkPlayerCounter(); // may throw

也就是说,除非另有说明,否则任何阅读声明的人都应该始终假定函数可能会抛出异常。


推荐阅读