Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the what() message of boost::exception

Tags:

c++

boost

In the following code, I want to get the what() message of a boost::exception.

#include <iostream>
#include <boost/lexical_cast.hpp>
#include <boost/exception/diagnostic_information.hpp>

int main(void)
{
    try
    {
        int i(boost::lexical_cast<int>("42X"));
    }
    catch (boost::exception const &e)
    {
        std::cout << "Exception: " << boost::diagnostic_information_what(e) << "\n";
    }
    return 0;
}

When I run it, I get the message :

Exception: Throw location unknown (consider using BOOST_THROW_EXCEPTION)
Dynamic exception type: boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >

But when I do not catch the exception, the shell outputs :

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >'
  what():  bad lexical cast: source type value could not be interpreted as target
[1]    8744 abort      ./a.out

I want that message : bad lexical cast: source type value could not be interpreted as target; but I could not find the way to have it. The boost exception system is a mystery to me.

How to get this very message ?

Edit: boost::exception has no what() method. So, how the shell can it write std::exception::what: bad lexical cast: source type value could not be interpreted as target, since this is not an std::exception ?

like image 466
Boiethios Avatar asked Apr 21 '16 10:04

Boiethios


2 Answers

Catch it as bad_lexical_cast to use the method what():

catch (const boost::bad_lexical_cast& e)
{      //    ^^^^^^^^^^^^^^^^^^^^^^^
    std::cout << "Exception: " << e.what() << "\n";
                              //  ^^^^^^^^
}

And it will display Exception: bad lexical cast: source type value could not be interpreted as target

like image 87
Andreas DM Avatar answered Nov 09 '22 18:11

Andreas DM


From the diagnostic_information_what reference:

The diagnostic_information_what function is intended to be called from a user-defined std::exception::what() override.

The function is not supposed to give you the message from the what() function, it's supposed to be used in the what() function to create a message to return.

Then to continue, from the boost::lexical_cast reference:

If the conversion is unsuccessful, a bad_lexical_cast exception is thrown.

So lets take a look the bad_lexical_cast:

class bad_lexical_cast : public std::bad_cast

It inherits from the standard std::bad_cast which inherits from std::exception which have a what() member function.

So the solution is to catch boost::bad_lexical_cast (or std::exception) instead of boost::exception which is not involved at all.

like image 4
Some programmer dude Avatar answered Nov 09 '22 19:11

Some programmer dude