开发者

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. "ZeroDivis开发者_如何学编程ionError: 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.


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


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜