2

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.

prosseek
  • 182,215
  • 215
  • 566
  • 871
  • 1
    You shouldn't divide by zero ;) – default Jun 24 '10 at 21:17
  • Indeed; division by zero will invoke undefined behaviour. On Posix platforms it will raise SIGFPE rather than throwing a C++ exception, since that is the behaviour defined by Posix. – Mike Seymour Jun 25 '10 at 01:15
  • possible duplicate of [The python exception vs C++ exception handling](http://stackoverflow.com/questions/3113904/the-python-exception-vs-c-exception-handling) – bk1e Jun 25 '10 at 04:23

4 Answers4

4

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
  • 74,869
  • 16
  • 134
  • 187
  • 1
    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 Jun 25 '10 at 08:56
1

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

Puppy
  • 144,682
  • 38
  • 256
  • 465
1

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
  • 299,747
  • 42
  • 398
  • 622
1

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
  • 10,462
  • 8
  • 53
  • 69