我创建了以下异常类:
namespace json {
/**
* @brief Base class for all json-related exceptions
*/
class Exception : public std::exception { };
/**
* @brief Indicates an internal exception of the json parser
*/
class InternalException : public Exception {
public:
/**
* @brief Constructs a new InternalException
*
* @param msg The message to return on what()
*/
InternalException( const std::string& msg );
~InternalException() throw ();
/**
* @brief Returns a more detailed error message
*
* @return The error message
*/
virtual const char* what() const throw();
private:
std::string _msg;
};
}
实现:
InternalException::InternalException( const std::string& msg ) : _msg( msg ) { }
InternalException::~InternalException() throw () { };
const char* InternalException::what() const throw() {
return this->_msg.c_str();
}
我抛出这样的异常:
throw json::InternalException( "Cannot serialize uninitialized nodes." );
我想在 Boost::Test 单元测试中测试抛出异常的行为:
// [...]
BOOST_CHECK_THROW( json::write( obj ), json::InternalException ); //will cause a json::InternalException
但是,当异常发生时测试退出,就好像没有 try...catch 一样。
如果我明确地 try...catch 并用or包围json::write()
调用,我会得到相同的行为。引发了异常,但无论如何我都无法捕捉到它。try{ json.write(obj); }catch(const json::InternalException& ex){}
try{json.write(obj);}catch(...){}
我得到的输出如下:
terminate called after throwing an instance of 'json::InternalException'
what(): Cannot serialize uninitialized nodes.
我在这里做错了什么?