prosseek
prosseek

Reputation: 190709

How can I know the name of the exception in C++?

With Python, I could get the name of the exception easily as follows.

  1. run the code, i.e. x = 3/0 to get the exception from python
  2. "ZeroDivisionError: integer division or modulo by zero" tells me this is ZeroDivisionError
  3. Modify the code i.e. try: x=3/0 except ZeroDivisionError: DO something

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

Answers (4)

DanDan
DanDan

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

Mark Ransom
Mark Ransom

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

Puppy
Puppy

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

R Samuel Klatchko
R Samuel Klatchko

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

Related Questions