Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know the exception type for std::exception

Tags:

c++

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)

like image 280
user3587624 Avatar asked May 06 '26 18:05

user3587624


2 Answers

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.

like image 121
Brian Bi Avatar answered May 09 '26 08:05

Brian Bi


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.

like image 20
463035818_is_not_a_number Avatar answered May 09 '26 09:05

463035818_is_not_a_number



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!