Reputation: 190709
With Python, I could get the name of the exception easily as follows.
Is there any similar way to find the exception name with C++?
When I run the x = 3/0, the compiled binary just throws 'Floating point exception', which is not so useful compared to python.
Upvotes: 2
Views: 979
Reputation: 10562
If this is a debugging issue, you may be able to set your compiler to break when it hits an exception, which can be infinitely useful.
Upvotes: 1
Reputation: 308121
For most exceptions if you have the RTTI option set in your compiler, you can do:
catch(std::exception & e)
{
cout << typeid(e).name();
}
Unfortunately the exception thrown by a divide by zero does not derive from std::exception, so this trick will not work.
Upvotes: 1
Reputation: 146910
If you want to know the name of the exception class, you could use RTTI. However, the vast majority of C++ code will throw an exception derived from std::exception.
However, all you get is the exception data contained in std::exception::what, and you can get the name of the exception class from RTTI and catch that explicitly if you need more information (and it contains more information).
Upvotes: 1
Reputation: 76531
While you can't easily ask for the name of the exception, if the exception derives from std::exception
you can find out the specified reason it was shown with what()
:
try
{
...
}
catch (const std::exception &exc)
{
std::err << exc.what() << std::endl;
}
On a side note, dividing by 0 is not guaranteed to raise a C++ exception (I think the MS platforms may do that but you won't get that on Linux).
Upvotes: 4