Krishna
Krishna

Reputation: 1382

stdexcept vs exception Headers in c++

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?

Upvotes: 49

Views: 19995

Answers (3)

snakedoctor
snakedoctor

Reputation: 305

exception is for the user to inherit and define their own exceptions.

stdexcept is for catching and handling the standard exceptions

Upvotes: 3

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136425

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.

Upvotes: 13

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42929

  • <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.

Upvotes: 64

Related Questions