Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 682
Krishna Oza Avatar asked Aug 06 '14 14:08

Krishna Oza


People also ask

Do I need to include Stdexcept?

The Standard does not require that <stdexcept> includes <exception> at all.

What is Stdexcept library in C++?

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.

What is the use of exception header?

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.

How do you throw an exception in CPP?

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.


Video Answer


2 Answers

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

like image 71
101010 Avatar answered Sep 29 '22 07:09

101010


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.

like image 40
Maxim Egorushkin Avatar answered Sep 29 '22 06:09

Maxim Egorushkin