What type of exception should I throw?

后端 未结 5 1177
难免孤独
难免孤独 2020-12-08 03:40

After going through some links on exception handling (1, 2, and 3), I know that C++ programs can throw pretty much anything as exceptions (int, char*

5条回答
  •  情歌与酒
    2020-12-08 04:21

    Here is a code snippet that shows how to extend and use the std::exception class: (BTW, this code has a bug, which I will explain later).

    #include 
    #include 
    #include 
    
    class my_exception : public std::exception
    {
    public:
       explicit my_exception(const std::string& msg)
          : msg_(msg)
       {}
    
       virtual ~my_exception() throw() {}
    
       virtual const char* what() const throw()
       {
          return msg_.c_str();
       }
    
    private:
       std::string msg_;
    };
    
    void my_func() throw (my_exception&)
    {
      throw my_exception("aaarrrgggg...");
    }
    
    int
    main()
    {
      try
        {
          my_func();
        }
      catch (my_exception& ex)
        {
          std::cout << ex.what() << '\n';
        }
      return 0;
    }
    

    Note that the constructor is explicit and the destructor and what() are declared (using throw()) to indicate that they themselves will not throw exceptions. This is where the bug is. Is it guaranteed that the call to msg_.c_str() will not throw exceptions of its own? What about the string constructor we are using to initialize msg_? It can also raise exceptions. How can we design an exception class that is safe from exceptions raised by member objects? The answer is - inherit from std::runtime_error or a similar std::exception subclass. So the proper way to implement my_exception would be:

    class my_exception : public std::runtime_error
    {
    public:
        my_exception(const std::string& msg) 
            : std::runtime_error(msg)
        { }
    };
    

    We need not override what(), as it is already implemented in std::runtime_error. Proper handling of the message buffer is done by std::runtime_error, so we can be sure that my_exception itself will not throw some unknown error at runtime.

提交回复
热议问题