自定义异常what()返回“std::Exception”

问题描述 投票:0回答:1

在这里,我刚刚构建了一个自定义异常,但在抛出并捕获它之后,异常的 What 方法没有返回应有的原因。相反,它只是返回“std::exception”。

#include <stdexcept>
#include <iostream>
#include <cstring>

class CustomException: public std::exception {
  public: std::string m_reason;
  CustomException(std::string reason): m_reason(reason) {}
  const char * what() {
    return m_reason.c_str();
  }
};

void
function () {
  throw CustomException("no reason");
}

int main() {
  try {
    function ();
  } catch (const std::exception & e) {
    std::cout << e.what() << std::endl;
  }
}
c++ exception
1个回答
0
投票

我花了很长时间才弄清楚什么方法缺少

const noexcept override
注释来正确重写具有签名
what
的 std::exception 类的
virtual const char* what() const noexcept;
方法(自 C++11 起)

#include <stdexcept>
#include <iostream>
#include <cstring>

class CustomException: public std::exception {
  public: std::string m_reason;
  CustomException(std::string reason): m_reason(reason) {}
  const char * what() const noexcept override{
    return m_reason.c_str();
  }
};

void
function () {
  throw CustomException("no reason");
}

int main() {
  try {
    function ();
  } catch (const std::exception & e) {
    std::cout << e.what() << std::endl;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.