C++ catch(std::exception & e ) vs. catch(…)

后端 未结 4 1880
傲寒
傲寒 2020-12-11 03:58

I know the difference in handling of both of these catches, but what does it take for the ellipse to catch something the std::exception catch wouldn\'t catch?

For ex

相关标签:
4条回答
  • 2020-12-11 04:15

    While it's definitely a good idea to do so, you don't have to derive your custom exceptions from std::exception. C++ allows you to throw practically any object type.

    So throw 1; will not be handled by your first handler, for example. And neither will...

    class MyCustomException { // Doesn't derive
     ///
    };
    

    ... if it was thrown.

    0 讨论(0)
  • 2020-12-11 04:22

    As written, the throw statement throws an object whose type is derived from std::exception, so it's caught by the first catch clause. If you change the throw to throw 3; the exception will be caught by the second catch clause, not the first.

    0 讨论(0)
  • 2020-12-11 04:33
    catch(const std::exception& e)
    

    Will catch std exceptions only.

    catch(...)
    

    Will catch everything there after.

    You can handle integers and other types (http://www.cplusplus.com/doc/tutorial/exceptions/)

    For example:

    catch(int e)
    
    0 讨论(0)
  • 2020-12-11 04:34

    You probably meant:

    throw std::runtime_error("runtime error!"); // not std::runtime
    

    The std::runtime_error is derived from the std::exception so your first catch block is fired up as it catches exceptions of type std::exception. And there you probably meant:

    std::cout << "Exception: " << e.what(); // not e
    

    If you threw anything else other than the std::run_time or std::exception and its derivatives, the second catch block would be triggered. Useful reading from the C++ FAQ: What should I throw?

    0 讨论(0)
提交回复
热议问题