在这里,我刚刚构建了一个自定义异常,但在抛出并捕获它之后,异常的 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;
}
}
我花了很长时间才弄清楚什么方法缺少
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;
}
}