Why did the C++ standard bother inventing the std::exception classes? What’s their benefit? My reason for asking is this:
try
{
throw std::string("boom");
}
catch (std::string str)
{
std::cout << str << std::endl;
}
Works fine. Later, if I need, I can just make my own lightweight “exception” types. So why should I bother with std::exception?
It provides a generic and consistent interface to handle exceptions thrown by the standard library. All the exceptions generated by the standard library are inherited from
std::exception.Note that standard library api’s can throw a number of different kinds of exceptions, To quote a few examples:
std::bad_allocstd::bad_caststd::bad_exceptionstd::bad_typeidstd::logic_errorstd::runtime_errorstd::bad_weak_ptr | C++11std::bad_function_call | C++11std::ios_base::failure | C++11std::bad_variant_access | C++17and so on…
std::exceptionis the base class for all these exceptions:providing a base class for all these exceptions, allows you to handle multiple exceptions with a common exception handler.
If I need, I can just make my own lightweight “exception” types. So why should I bother with
std::exception?If you need your custom exception class go ahead and make one. But
std::exceptionmakes your job easier because it already provides a lot of functionality which a good exception class should have. It provides you the ease of deriving from it and overidding necessary functions(in particularstd::exception::what()) for your class functionality.This gives you 2 advantages the
std::exceptionhandler,Image courtesy: http://en.cppreference.com/w/cpp/error/exception