mar*_*man 12 c++ exception throw
我正在编写一组扩展的自定义异常std::exception.在某些代码中,当捕获异常时,我只是重新throw启动链,直到驱动程序main函数调用catches并打印结果.但是,最终打印的所有内容都是"std :: exception".这似乎不是我之前处理的范围问题.
为什么我的异常消息不能打印?
我的异常代码:
// General exception class
struct MyException : public std::exception
{
std::string _msg;
MyException(const std::string &exception_name) : _msg(exception_name) {}
void setMessage(const std::string &message)
{
_msg += ": " + message + "\n";
}
void setLocation(const char * func, const char * file, const int line)
{
_msg += " In function " + std::string(func) + "(" + file + ":" + std::to_string(line) + ")";
}
const char * what() const throw()
{
return _msg.c_str();
}
};
// Specializations of the MyException
struct FileNotFoundException : public MyException
{
FileNotFoundException() : MyException("FileNotFoundException") {}
};
struct IOException : public MyException
{
IOException() : MyException("IOException") {}
};
struct DBException : public MyException
{
DBException() : MyException("DBException") {}
};
Run Code Online (Sandbox Code Playgroud)
我的所有异常抛出都包含在这个宏中
#define EXCEPTION_THROWER(ET, message) \
{ \
ET e; \
e.setMessage(message); \
e.setLocation(__func__, __FILE__, __LINE__); \
throw e; \
}
Run Code Online (Sandbox Code Playgroud)
并称为
EXCEPTION_THROWER(DBException, "Blah blah database exception")
Run Code Online (Sandbox Code Playgroud)
中间try/catch块如下所示:
try
{
// Call a function that throws an exception
}
catch(const std::exception &e)
{
throw e; // Forward any exceptions
}
Run Code Online (Sandbox Code Playgroud)
和驱动程序代码都在一个try与一个块catch (const std::exception &e)的块.