无法捕获我的异常

Can't catch my exception

本文关键字:我的 异常      更新时间:2023-10-16

我创建了以下异常类:

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{ json.write(obj); }catch(const json::InternalException& ex){}甚至try{json.write(obj);}catch(...){}包围json::write()调用,我得到相同的行为。异常被提出,但无论如何我都抓不到它。

我得到的输出如下:

terminate called after throwing an instance of 'json::InternalException'
what():  Cannot serialize uninitialized nodes.

我在这里做错了什么?

我找到了。我在试图为你们一起举办 SSCCE 时想通了。我json::write()用投掷说明符声明,但没有包括json::InternalException.

现在,将抛出说明符调整为正确的异常可以让我实际捕获它。感谢您的所有提示。