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 |
|---|---|
| 1 | std::exception This is an exception and parent class of all the standard C++ exceptions. |
| 2 | std::bad_cast It is an exception thrown by dynamic_cast. |
| 3 | std::bad_exception This exception is used to handle the unexpected exceptions in a C++ program. |
| 4 | std::bad_alloc It is generally be thrown by new. |
| 5 | std::logic_failure This exception can be detected by reading a code. |
| 6 | std::runtime_error This exception cannot be detected by reading a code. |
| 7 | std::bad_typeid It is an exception thrown by typeid. |
Keywords
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 {
public:
Sample1() {
cout << "Construct an Object of sample1" << endl;
}
~Sample1() {
cout << "Destruct an Object of sample1" << endl;
}
};
class Sample2 {
public:
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;
}
}Output
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) {
}
}Output
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.