user3587624
user3587624

Reputation: 1471

How to know the exception type for std::exception

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

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

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

Brian Bi
Brian Bi

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

Related Questions