views:

108

answers:

4

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.

+4  A: 

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).

R Samuel Klatchko
Win32 platforms can raise a SEH `EXCEPTION_FLT_DIVIDE_BY_ZERO` exception (0xC000008E). There's also an integer variant, `EXCEPTION_INT_DIVIDE_BY_ZERO == 0xC0000094`
MSalters
+1  A: 

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).

DeadMG
+1  A: 

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.

Mark Ransom
Also note that the format of typeid(foo).name() is implementation-defined; on some platforms, it's mangled.
Josh Kelley
+1  A: 

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.

DanDan