【问题标题】:what does what() const throw mean?what() const throw 是什么意思?
【发布时间】:2020-05-10 09:04:11
【问题描述】:

C++ concurrency in Action 第 45 页我有这段代码

#include <exception>
#include <memory>

struct empty_stack: std::exception
{
   const char* what() const throw();  //<--- what does this mean?
}

谁能告诉我这是什么意思?

这个empty_stack异常被另一个函数抛出,如果栈是空的,比如

if(data.empty()) throw empty_stack();

但里面的线是什么意思?

编辑:

有人发布(但被删除了!想知道为什么)这个link 谢谢!

【问题讨论】:

  • 它声明了返回异常描述的方法what()。您是指整行还是其中的某个特定部分?
  • 整行。那么what 只是一个方法的名称? (ergo 可以是什么?)
  • @KansaiRobot std::exception 提供了一个虚方法what,所以不行,你必须使用这个特定的名称来覆盖它。
  • @Evg -- throw()noexcept 不太一样。见here。不同之处在于,如果函数抛出异常,如果它被标记为throw(),您将获得对std::unexpected() 的调用;如果它被标记为noexcept,您将接到std::terminate() 的电话。 std::unexpected() 默认调用std::terminate(),但它是可替换的,所以你不必终止。

标签: c++ c++11


【解决方案1】:
 const char* what() const throw();
 |-> return type
             |-> name of the method
                 |-> parameter
                    |-> it is a const method
                          |-> exception specification

这是一个名为whatconst 方法,它不接受任何参数,返回一个const char * 并指定不引发异常。

请注意,dynamic exception specifications 在 C++11 中已弃用,并在 C++17/20 中删除。对于它的作用,我引用cppreference

如果函数抛出其异常规范中未列出的类型的异常,则调用函数std::unexpected。默认函数调用std::terminate,但它可以被用户提供的函数(通过std::set_unexpected)替换,该函数可能调用std::terminate 或抛出异常。如果从std::unexpected 抛出的异常被异常规范接受,堆栈展开将照常继续。如果不是,但异常规范允许std::bad_exception,则抛出std::bad_exception。否则,将调用 std::terminate

【讨论】:

    猜你喜欢
    • 2017-02-23
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 2011-08-27
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多