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
?
Basically, Java custom exceptions are used to customize the exception according to user needs. In simple words, we can say that a User-Defined Exception or custom exception is creating your own exception class and throwing that exception using the 'throw' keyword.
The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions.
In terms of Functionality Checked and Unchecked Exception are same. Checked Exception handling verified during compile time while Unchecked Exception is mostly programming errors.
The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java programs.
Why did the C++ standard bother inventing the
std::exception
classes? What's their benefit?
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_alloc
std::bad_cast
std::bad_exception
std::bad_typeid
std::logic_error
std::runtime_error
std::bad_weak_ptr | C++11
std::bad_function_call | C++11
std::ios_base::failure | C++11
std::bad_variant_access | C++17
and so on...std::exception
is 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::exception
makes 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 particular std::exception::what()
) for your class functionality.
This gives you 2 advantages the std::exception
handler,
Image courtesy: http://en.cppreference.com/w/cpp/error/exception
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With