How do exceptions work in C++

In C++, Exception Handling is a process to handle runtime errors. Exception is an event which is thrown at runtime in C++. All exceptions are derived from std::exception class. It is a runtime error which can be handled. It prints exception message and terminates the program, if we don't handle the exception.

Exceptions are defined in C++ standard as <exception> class that we can use inside our programs. The arrangement of parent-child class hierarchy has been shown below −

Common exception classes in C++ are −

Sr.No.Exception & Description
This is an exception and parent class of all the standard C++ exceptions.
It is an exception thrown by dynamic_cast.
This exception is used to handle the unexpected exceptions in a C++ program.
It is generally be thrown by new.
This exception can be detected by reading a code.
This exception cannot be detected by reading a code.
It is an exception thrown by typeid.


There are 3 keywords in exception handling: try, catch and throw.

Try/Catch block

In C++, exception handling is performed using try/catch statement. The code that may occur exception is used to place by Try block. Catch block is used to handle the exception.

Example Code

#include <iostream>
using namespace std;
class Sample1 {
      Sample1() {
         cout << "Construct an Object of sample1" << endl;
      ~Sample1() {
         cout << "Destruct an Object of sample1" << endl;
class Sample2 {
      Sample2() {
         int i=7;
         cout << "Construct an Object of sample2" << endl;
         throw i;
      ~Sample2() {
         cout << "Destruct an Object of sample2" << endl;
int main() {
   try {
      Sample1 s1;
      Sample2 s2;
   } catch(int i) {
         cout << "Caught " << i << endl;


Construct an Object of sample1
Construct an Object of sample2
Destruct an Object of sample1
Caught 7

User Defined Exception

We can define our own exceptions by inheriting and overriding exception class functionalities.

Example Code

#include <iostream>
#include <exception> using namespace std;
struct DivideByZero : public exception {
   const char * what () const throw () {
      return "My Exception";
int main() {
   try {
      throw DivideByZero();
   } catch(DivideByZero& e) {
      cout << "Exception caught" << endl; cout << e.what() << endl;
   } catch(exception& e) {


Exception caught My Exception
what() = A public method provided by exception class and it has been overridden by all the child exception classes. It returns the cause of an exception.

Updated on: 30-Jul-2019


Kickstart Your Career

Get certified by completing the course

Get Started