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?
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.
Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.
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.
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.
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.
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