1

我创建了以下异常类:

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.

我在这里做错了什么?

4

1 回答 1

1

我找到了。我在尝试为你们一起举办 SSCCE 时发现了这一点。我已经json::write()声明了一个 throw 说明符,但没有包含json::InternalException.

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

于 2013-11-12T09:00:07.957 回答