Given this sample code:
#include <iostream>
#include <stdexcept>
class my_exception_t : std::exception
{
public:
explicit my_exception_t()
{ }
virtual const char* what() const throw()
{ return "Hello, world!"; }
};
int main()
{
try
{ throw my_exception_t(); }
catch (const std::exception& error)
{ std::cerr << "Exception: " << error.what() << std::endl; }
catch (...)
{ std::cerr << "Exception: unknown" << std::endl; }
return 0;
}
I get the following output:
Exception: unknown
Yet simply making the inheritance of my_exception_t
from std::exception
public
, I get the following output:
Exception: Hello, world!
Could someone please explain to me why the type of inheritance matters in this case? Bonus points for a reference in the standard.
When you inherit privately, you cannot convert to or otherwise access that base class outside of the class. Since you asked for something from the standard:
Simply put, to anything outside the class it's like you never inherited from
std::exception
, because it's private. Ergo, it will not be able to be caught in thestd::exception&
clause, since no conversion exists.The type of inheritance doesn't matter. It only matters that you have an accessible conversion available to one of the catch types. It just so happens that since it is not public inheritance there is no public accessible conversion.
Explanation:
You can see the same behavior here:
A thrown exception is only caught by a catch block if: