Question

std::system_error handles exception with associated error code. Is it possible using common catch block to get std::system_error exception message and it's code? Like this

try{
    // code generating exception
} catch (const std::exception& ex){ // catch all std::exception based exceptions
    logger.log() << ex.what();      // get message and error code
                                    // if exception type is system_error     
}

Is the only way is to catch directly std::system_error type and get its code before base exception type catching? What is the best approach to use std::system_error widely?

Was it helpful?

Solution

What is the best approach to use std::system_error widely?

The best approach in my opinion, is to catch the exception directly.

catch (const std::system_error& e) {
    std::cout << e.what() << '\n';
    std::cout << e.code() << '\n';
} catch (const std::exception& e) {
    std::cout << e.what() << '\n'; 
}

Is the only way is to catch directly std::system_error type and get its code before base exception type catching?

It's technically not the only way. It's the obvious and idiomatic way. You can use dynamic_cast.

catch (const std::exception& e) {
    std::cout << e.what() << '\n';
    auto se = dynamic_cast<const std::system_error*>(&e);
    if(se != nullptr)
        std::cout << se->code() << '\n';
}

But you mention in the comment that you prefer not to use dynamic_cast. It's possible to avoid that too, but not in any way that has any advantages.

Note that even if you can do things in non obvious ways, it doesn't mean that you should.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top