Get message what () exceptions boost :: exception

In the following code, I want to receive the what() message of 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 a 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 output:

 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 this message: bad lexical cast: source type value could not be interpreted as target ; but I could not find a way to get it. Forcing exclusion is a mystery to me.

How to receive this message?

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

+5
source share
2 answers

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

 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

+4
source

From the diagnostic_information_what link :

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

The function should not give you the message from the what() function, which should be used in the what() function to create the return message.

Then, to continue, the link boost::lexical_cast :

If the conversion fails, a bad_lexical_cast exception is thrown.

So let's see 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 member function what() .

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

+4
source

Source: https://habr.com/ru/post/1247603/


All Articles