在字符串函数中抛出'char const*'实例后调用的终止

terminate called after throwing an instance of 'char const*' in string function

本文关键字:实例 调用 终止 const char 函数 字符串      更新时间:2023-10-16

如果参数不适合格式化,我想抛出消息。我其实不知道会发生什么。我试图用 std::string 抛出消息,但不起作用。这是怎么回事?

此外,编译器给出了"中止调用"消息。

我在打开之前搜索了该主题,但找不到满意的答案。

string timeConversion(string s) {
// hh:mm:ss:AM
if(s.length() != 11)
throw "message";
return something;
}

编辑:代码简化。

不要抛出字符串 (const char*(:

throw "failed because of hour";

破例class

class MyException : public std::exception
{
public:
MyException(const char* err) : std::exception(err) {}       
};

throw

throw MyException("failed because of hour");

然后catch它:

try
{
// code that might throw
}
catch(const MyException& ex)
{
// process exception
}

如果引发异常但未捕获(当前情况(,则调用terminate