Should I inherit from std::exception?

前端 未结 14 1483
有刺的猬
有刺的猬 2020-11-30 18:56

I\'ve seen at least one reliable source (a C++ class I took) recommend that application-specific exception classes in C++ should inherit from std::exception. I\

14条回答
  •  情歌与酒
    2020-11-30 19:52

    Though this question is rather old and has already been answered plenty, I just want to add a note on how to do proper exception handling in C++11, since I am continually missing this in discussions about exceptions:

    Use std::nested_exception and std::throw_with_nested

    It is described on StackOverflow here and here, how you can get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.

    Since you can do this with any derived exception class, you can add a lot of information to such a backtrace! You may also take a look at my MWE on GitHub, where a backtrace would look something like this:

    Library API: Exception caught in function 'api_function'
    Backtrace:
    ~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
    ~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"
    

    You don't even need to subclass std::runtime_error in order to get plenty of information when an exception is thrown.

    The only benefit I see in subclassing (instead of just using std::runtime_error) is that your exception handler can catch your custom exception and do something special. For example:

    try
    {
      // something that may throw
    }
    catch( const MyException & ex )
    {
      // do something specialized with the
      // additional info inside MyException
    }
    catch( const std::exception & ex )
    {
      std::cerr << ex.what() << std::endl;
    }
    catch( ... )
    {
      std::cerr << "unknown exception!" << std::endl;
    }
    

提交回复
热议问题