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:
We have placed a handler that catches exception objects by reference (notice the ampersand & after the type), therefore this catches also classes derived from exception, like our myex object of class myexception.
Does this mean that by using “&” you can also catch exception of the parent class? I thought & is predefined in std::exception because it’s better to pass e (std::exception) as reference than object.
The reason for using
&with exceptions is not so much polymorphism as avoiding slicing. If you were to not use&, C++ would attempt to copy the thrown exception into a newly createdstd::exception, potentially losing information in the process. Example:This will print the default message for
std::exception(in my case,St9exception) rather thanHello, world!, because the original exception object was lost by slicing. If we change that to an&:Now we do see
Hello, world!.