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 がなかったかのように例外が発生すると、テストは終了します。

json::write()try...catch を明示的に作成し、呼び出しをtry{ json.write(obj); }catch(const json::InternalException& ex){}or で囲むとtry{json.write(obj);}catch(...){}、同じ動作が得られます。例外が発生しますが、どうしてもキャッチできません。

私が得る出力は次のとおりです。

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

ここで何が間違っていますか?

4

1 に答える 1