抛出一个字符串确实是个坏主意。
在你的代码中,你抛出了一个 const char*
。抛出内置类型(比如 int
、float
,或者像这种情况下的 const char*
)是个坏主意,因为这些内置类型没有提供适当的上下文错误信息。实际上,当捕获到异常时,理解异常的原因是很重要的,以便采取适当的措施。但是内置类型并不能提供此类信息,导致在捕获异常时难以理解异常的原因和根本原因。
此外,抛出内置类型也会令人困惑,因为这不是现代 C++ 的惯用方式。在 C++ 中,抛出异常的惯用方式是定义一个适当的 C++ 类来表示异常,通常从 std::exception 派生它,或者从其他派生自 std::exception 的类派生它,然后抛出该异常类的实例。
您还可以简单地抛出 C++ 标准库中已定义的一些异常类,比如 std::runtime_error。
例如,您可以抛出一个 std::runtime_error,将错误消息字符串传递给构造函数,像这样:
throw std::runtime_error("Your error message");
在捕获点,你可以通过常量引用(const &)捕获runtime_error异常,并调用what()方法获取错误字符串。
try {
...
} catch (const std::runtime_error& ex) {
}
但是不要抛弃这个“裸露”的字符串。
如果你想定义一个自定义的异常类,你可以从
std::runtime_error
派生它,就像这样:
class YourCustomException
: public std::runtime_error
{
public:
YourCustomException(const char* message)
: std::runtime_error(message) {
}
YourCustomException(const std::string& message)
: std::runtime_error(message) {
}
};
像这样扔出去:
throw YourCustomException("Your error message");
抓住它就像这样:
try {
...
} catch (const YourCustomException& ex) {
}