C ++自定义异常消息未显示 [英] C++ custom exception message not displaying
问题描述
我试图创建一个自定义的异常类,将其抛出并显示错误消息,但是我做错了事,导致未引发该异常并且该消息未得到打印.
I am trying to create a custom exception class, throw it, and display the error message, but I am doing something wrong, causing the exception to not get thrown and the message to not get printed.
这是异常类:
class UnbalancedParenthesesException : public std::exception {
int line_number {0};
public:
UnbalancedParenthesesException(int line_number) :
line_number { line_number }
{}
virtual const char* what() const throw() {
std::string exception_message =
"Papentheses imbalance at line " + std::to_string(line_number) + "\n";
return exception_message.c_str();
}
};
我正尝试 try
/ throw
/ catch
,如下所示:
I am trying totry
/throw
/catch
as follows:
void handle_closed_paren(int line_number) {
try {
if (definitely_unbalanced()) {
throw UnbalancedParenthesesException(line_number);
}
} catch (const UnbalancedParenthesesException& e) {
std::out << e.what() << "\n";
}
控制台中与此错误无关.
There is nothing pertinent to this error in the console.
谢谢.
推荐答案
当您在 std :: string 上返回
c_str()
的结果时,您的程序具有未定义的行为代码>超出范围.任何事情都可能发生.
Your program has undefined behaviour as you are returning the result of c_str()
on a std::string
that goes out of scope. Anything could happen.
除此之外,如果您没有看到异常,则不会引发异常,可能是因为 definitely_unbalanced()
的结果是错误的.
Beyond that, if you're not seeing an exception then one was not thrown, probably because the result of definitely_unbalanced()
is falsey.
使用调试器逐步执行程序.
Step through your program using your debugger.
这篇关于C ++自定义异常消息未显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!