Please tell me how to use try/catch properly with boost::exception.
This is one of examples
void Settings::init(const std::string &filename)
{
using boost::property_tree::ptree;
try
{
read_xml(filename, pt);
}
catch(boost::exception const& ex)
{
LOG_FATAL("Can't init settings. %s", /* here is the question */);
}
}
Do I need catch std::exception too? I can't let my application fail, so I just need to log everything.
UPD: I also can't understand now to retrive information for logging from exception???
The recommendation is to have specific boost exception classes derive (virtually) from both boost::exception and std::exception , and not just from boost::exception . Some boost libraries' exceptions derive only from std::exception (like boost::bad_lexical_cast ), some from both (like boost::xpressive::regex_error ).
boost::throw_exception(x); is a replacement for throw x; that both degrades gracefully when exception handling support is not available, and integrates the thrown exception into facilities provided by Boost.
Exception handling is used to handle the exceptions. We can use try catch block to protect the code. Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.
Generally, you should only catch exceptions that you know how to handle. The purpose of exceptions bubbling up is to allow other parts of the code catch them if they can handle them, so catching all exceptions at one level is probably not going to get you a desired result.
std::exception
has a member function called what()
that returns a const char*
that might explain what happened. If you want to log it (guessing that LOG_FATAL
wraps printf
somehow) you can do:
catch(std::exception const& ex)
{
LOG_FATAL("Can't init settings. %s", ex.what());
}
For boost::exception
though you can use boost::get_error_info
to find out more about it.
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