Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::system_error usage with common catch std::exception block

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?

like image 392
vard Avatar asked May 14 '14 10:05

vard


People also ask

What is std :: System_error?

std::system_error is the type of the exception thrown by various library functions (typically the functions that interface with the OS facilities, e.g. the constructor of std::thread) when the exception has an associated std::error_code, which may be reported.

Does catch catch all exceptions C++?

Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.

How to deal with errors C++?

In modern C++, in most scenarios, the preferred way to report and handle both logic errors and runtime errors is to use exceptions. It's especially true when the stack might contain several function calls between the function that detects the error, and the function that has the context to handle the error.

How do you catch anything in C++?

You can use catch(...) to catch EVERYTHING, but then you don't get a an object to inspect, rethrow, log, or do anything with exactly. So... you can "double up" the try block and rethrow into one outer catch that handles a single type.


1 Answers

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.

like image 155
eerorika Avatar answered Oct 21 '22 21:10

eerorika