catching std::exception by reference?

后端 未结 4 1060
时光取名叫无心
时光取名叫无心 2021-02-01 05:30

I have a silly question. I read this article about std::exception http://www.cplusplus.com/doc/tutorial/exceptions/

On catch (exception& e), it says:

4条回答
  •  梦谈多话
    2021-02-01 06:14

    Does this mean that by using "&" you can also catch exception of the parent class?

    No, this doesn't increase the scope of where you will catch exceptions from (e.g. from the parent class of the class that contains the try/catch code).

    It also doesn't increase the types of exceptions that can be caught, compared to catching by value (catch(std::exception e) without the & - you'll still catch each exception that either is std::exception or derives from it).

    What it increases is the amount of data that you will actually get when you catch the exception.

    If an exception is thrown that derives from std::exception, and you catch it by value, then you are throwing out any extra behavior in that exception class. It breaks polymorphism on the exception class, because of Slicing.

    An example:

    class MyException : public std::exception
    {
    public:
        virtual const char* what() const
        {
            return "hello, from my exception!";
        }
    };
    
    // ...
    
    try
    {
        throw MyException();
    }
    catch(std::exception& e)
    {
        // This will print "hello, from my exception!"
        std::cout << e.what() << "\n";
    }
    
    // ...
    
    try
    {
        throw MyException();
    }
    catch(std::exception e)
    {
        // This will print "Unknown exception"
        std::cout << e.what() << "\n";
    }
    

提交回复
热议问题