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
?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With