Exception Handling in C++

Exception Handling in C++: The exception handling in C++ is the process to handle runtime errors.  A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. All exceptions are derived from std:: exception class. It is a runtime error that can be handled. If we don’t handle the exception, it prints the exception message and terminates the program.



Exception Handling in C++

In C++ exception handling can be done by using the three keywords. They are as follows:

  • try: represents a block of code that can throw an exception.
  • catch: represents a block of code that is executed when a particular exception is thrown.
  • throw: Used to throw an exception. Also used to list the exceptions that a function throws, but doesn’t handle itself.

C++ Common Exceptions

Exception Description
std::exception an exception and parent class of all standard C++ exceptions
std::logic_failure an exception that can be detected by reading a code
std::runtime_error the exception that cannot be detected by reading a code
std::bad_exception used to handle the unexpected exceptions in a c++ program
std::bad_cast the exception is generally be thrown by dynamic_cast
std::bad_typeid an exception is generally be thrown by typeid
std::bad_alloc the exception is generally be thrown by new

Exceptions derived directly from the exception class

Exception Description
bad_alloc occurs when there is a failure of memory allocation
bad_cast Is thrown when dynamic_cast is used incorrectly
bad_exception is thrown by the unexpected handler
bad_function_call Thrown when an empty (not implemented) function is called
bad_typeid Thrown by typeid function
bad_weak_ptr An exception that can be thrown by the shared_ptr class constructor
ios_base::failure Base class for all the stream exceptions
logic_error Base class for some logic error exceptions
runtime_error Base class for some runtime error exceptions

Exception derived directly from exception class through logic_error

Exception Description
domain_error Thrown when an error of function domain happens
future_error Reports an exception that can happen in future objects(See more info about future class)
invalid_argument An exception is thrown when an invalid argument is passed
length_error Is thrown when the incorrect length is set
out_of range error thrown when out of range index is used

 Exceptions that are derived indirectly from exception class through runtime_error

Exception Description
overflow_error Arithmetic overflow exception
range_error Signals range error in computations
system_error Reports an exception from the operating system
underflow_error Arithmetic underflow exceptions