From the cplusplus.com reference for <exception>
and that for <stdexcept>
, it appears that <exception>
is sufficient for exception handling in C++98 or higher versions of C++.
Why does C++ have two headers files for exception handling? How does this affect my development? Which header should I use?
The Standard does not require that <stdexcept> includes <exception> at all.
C++ Library - <stdexcept> It is an exception classes and this header defines a set of standard exceptions that both the library and programs can use to report common errors.
C++ provides a list of standard exceptions defined in header <exception> in namespace std where “exception” is the base class for all standard exceptions. All exceptions like bad_alloc, bad_cast, runtime_error, etc generated by the standard library inherit from std::exception.
An exception in C++ is thrown by using the throw keyword from inside the try block. The throw keyword allows the programmer to define custom exceptions. Exception handlers in C++ are declared with the catch keyword, which is placed immediately after the try block.
<stdexcept>
: Defines a set of standard exceptions that both the library and programs can use to report common errors.
<exception>
: Defines the base class (i.e., std::exception
) for all exceptions thrown by the elements of the standard library, along with several types and utilities to assist handling exceptions.
So, <exception>
only defines the class std::exception
, while <stdexcept>
defines several classes that inherit from std::exception
(e.g., std::logic_error
, std::out_of_range
). That is why <stdexcept>
includes <exception>
.
They are in separate headers because if you want to define your own exception class inheriting std::exception
(and not use the classes from <stdexcept>
), you can avoid unnecessary definitions.
One practical consideration is that <stdexcept>
requires std::string
definition (exception constructors accept std::string
and have std::string
data member), whereas to catch and query std::exception
std::string
declaration or definition is not required.
In other words, std::exception
handler only needs <exception>
. The throw site requires the header of a particular exception class it throws.
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