C++异常类扩展语法

C++ exception class extension syntax

本文关键字:语法 扩展 异常 C++      更新时间:2023-10-16

我正在在线上课,遇到了一些我不确定我是否理解的语法。

    #include <iostream>
    #include <exception>
    using namespace std;
    class derivedexception: public exception {
          virtual const char* what() const throw() {
            return "My derived exception";
  }        
    } myderivedexception;
    int main() {
          try {
            throw myderivedexception;
          }
          catch (exception& e) {
            cout << e.what() << 'n';
          }
    }

我的问题是:

    virtual const char* what() const throw() 

这句话是什么意思?

另外,什么是

    } myderivedexception;

在类声明的末尾?

这一行:

  virtual const char* what() const throw() 

what 是一个虚拟方法,它返回指向常量char的指针(这意味着它可用于返回字符串文字,或通过调用 String::c_str(( 函数获得的 std::string 的内容(,本身是常量,因此它不会修改任何类成员,也不会引发任何异常。

这一行:

   } myderivedexception;

创建名为 myderivedexceptionderivedexception 类的实例。您可能不想这样做,而是抛出一个未命名的异常:

throw derivedexception();