I am trying to give the user the option to catch all the errors from my class or to catch them individually. I can catch individual exceptions but I can't catch it correctly when I try to catch the base error class. I get the standard error from std::exception "Unknown Error".
I have tried to catch the base exception and to catch the derived errors.
Can I have all my errors be a base error type and catch them all as such?
#include <iostream>
#include <exception>
struct FooException
: public std::exception
{
};
struct FooRuntimeException
: public std::runtime_error,
public FooException
{
FooRuntimeException(const char* what)
: runtime_error(what) {}
};
struct FooRangeError
: public std::range_error,
public FooException
{
FooRangeError(const char* what)
: range_error(what) {}
};
class Foo
{
public:
Foo() = default;
~Foo() {};
void throwRunTimeException()
{
throw FooRuntimeException("Runtime Error");
}
void throwRangeError()
{
throw FooRuntimeException("Range Error");
}
};
int main()
{
try
{
auto foo = Foo();
foo.throwRunTimeException();
}
catch (const FooException &e)
{
std::cerr << e.what(); // catches standard error message
}
return 0;
}
Is there a way to do this or is templates a possibility?