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.