Reputation: 1471
I have a try-catch block like below
try
{
// Do something here.
}
catch (const std::exception &e)
{
// std exception.
}
catch(...)
{
// Unknown exception. We can't know the type.
}
I am reading some documentation from http://www.cplusplus.com/reference/exception/exception/ but to me it is not obvious how to know what exception type was caught when the code goes into the std::exception part.
Is there a way to get a string with the type of error? (I don't want to surface the error message, just the exception type)
Upvotes: 3
Views: 1016
Reputation: 122133
You can catch different exceptions with different catch
blocks:
try
{
// Do something here.
}
catch (const std::runtime_error& e)
{
// Handle runtime error
}
catch (const std::out_of_range& e)
{
// Handle out of range
}
catch (const std::exception &e)
{
// Handle all other exceptions
}
catch(...)
{
// Unknown exception. We can't know the type.
}
Of course it does not always make sense to have a seperate catch for every type of exception, so you still would need a way to tell what is the type of the exception within the catch(std::exception&)
block, for which I refer you to this answer.
Upvotes: 3
Reputation: 119069
Is there a way to get a string with the type of error?
Sort of. If you catch by reference (as you are doing in the above code), then you can apply typeid
to the exception to get some info about its dynamic type. This is made possible by the fact that std::exception
is a polymorphic type. However, there's no guarantee that std::type_info::name()
is a readable name for the type.
Upvotes: 5