Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly catch std and boost exceptions

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???

like image 451
nix Avatar asked Nov 15 '11 12:11

nix


People also ask

Is boost exception derived from STD 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 ).

How do you throw a boost exception?

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.

How do you catch all exceptions?

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.

Should you catch all 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.


1 Answers

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.

like image 190
Flexo Avatar answered Sep 23 '22 19:09

Flexo