Exception Handling in C++
Last Updated on: 22nd Dec 2025 15:05:32 PM
1. Introduction to Exception Handling in C++
In C++, Exception Handling is a powerful mechanism used to handle runtime errors in a program in a graceful and controlled manner.
Instead of terminating the program abruptly when an error occurs, exception handling allows the program to:
-
Detect the error
-
Transfer control to a special block
-
Handle the error properly
-
Continue or terminate safely
2. What is an Exception?
An exception is an unexpected runtime problem that disrupts the normal flow of program execution.
Examples of Exceptions:
-
Division by zero
-
Accessing invalid array index
-
File not found
-
Memory allocation failure
3. Real-Life Example of Exception Handling
Example: Traffic Signal System
-
Green → normal flow
-
Red → stop
-
Accident occurs → traffic police intervenes
π Accident = Exception
π Traffic police = Exception handler
Without police, traffic would collapse.
Without exception handling, programs crash.
4. Why Exception Handling is Needed?
Without exception handling
-
Program crashes suddenly
-
Poor user experience
-
Difficult debugging
With exception handling
-
Smooth error handling
-
Better program reliability
-
Cleaner and maintainable code
5. Keywords Used in Exception Handling
C++ provides three main keywords:
| Keyword | Purpose |
|---|---|
try |
Block where exception may occur |
throw |
Throws an exception |
catch |
Handles the exception |
6. Basic Syntax of Exception Handling
try {
// code that may cause exception
}
catch (exception_type) {
// code to handle exception
}
7. Simple Example of Exception Handling
If division by zero occurs, the program throws an exception and handles it safely.
Example
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 0;
try {
if (b == 0)
throw b;
cout << "Result: " << a / b << endl;
}
catch (int x) {
cout << "Error: Division by zero is not allowed" << endl;
}
return 0;
}
Output
Error: Division by zero is not allowed
Explanation of Output
-
Division by zero detected
-
Exception thrown using
throw -
catchblock handles the error
8. Multiple Catch Blocks
A program may face different types of exceptions, so multiple catch blocks are used.
Example
#include <iostream>
using namespace std;
int main() {
try {
throw 3.14;
}
catch (int x) {
cout << "Integer exception caught" << endl;
}
catch (double y) {
cout << "Double exception caught" << endl;
}
return 0;
}
Output
Double exception caught
Explanation of Output
-
Exception type is
double -
Matching
catchblock executes
9. Catch-All Handler ( catch(...) )
Used when you don’t know the type of exception.
Example
#include <iostream>
using namespace std;
int main() {
try {
throw 'A';
}
catch (...) {
cout << "Unknown exception caught" << endl;
}
return 0;
}
Output
Unknown exception caught
Explanation of Output
-
Handles all exception types
-
Should be placed at the end
10. Exception Handling with Functions
Exceptions can be thrown inside functions and caught in main().
Example
#include <iostream>
using namespace std;
void checkAge(int age) {
if (age < 18)
throw age;
else
cout << "Eligible for voting" << endl;
}
int main() {
try {
checkAge(16);
}
catch (int a) {
cout << "Not eligible. Age = " << a << endl;
}
return 0;
}
Output
Not eligible. Age = 16
Explanation of Output
-
Function throws exception
-
Main function handles it
11. Real-Life Use Case of Function Exception
Example: Online Exam System
-
If student age < required → exception
-
System shows proper error message
-
Exam not started
12. Nested Try-Catch Blocks
Concept Explanation
try blocks can exist inside another try block.
Example
#include <iostream>
using namespace std;
int main() {
try {
try {
throw 10;
}
catch (int x) {
cout << "Inner catch: " << x << endl;
throw;
}
}
catch (int y) {
cout << "Outer catch: " << y << endl;
}
return 0;
}
Output
Inner catch: 10
Outer catch: 10
Explanation of Output
-
Exception rethrown
-
Handled by outer catch
13. Standard Exception Classes in C++
C++ provides built-in exception classes in <exception>.
| Class | Description |
|---|---|
exception |
Base class |
bad_alloc |
Memory allocation failure |
out_of_range |
Index error |
runtime_error |
Runtime issue |
14. Example Using bad_alloc
Complete Program
#include <iostream>
using namespace std;
int main() {
try {
int *p = new int[100000000000];
}
catch (bad_alloc &e) {
cout << "Memory allocation failed" << endl;
}
return 0;
}
15. Advantages of Exception Handling
β Prevents program crash
β Improves reliability
β Separates error logic from normal logic
β Better debugging and maintenance
16. Disadvantages of Exception Handling
β Slight performance overhead
β Complex for beginners
β Misuse can make code unreadable
17. Common Mistakes
β Not catching thrown exception
β Catching wrong data type
β Using exceptions for normal logic
18. Interview Questions
-
What is exception handling?
-
Difference between error and exception?
-
What is
try,throw,catch? -
What is catch-all handler?
-
Can multiple catch blocks be used?
19. Real-World Applications
-
Banking software
-
Online payment systems
-
File handling systems
-
Game engines
-
Operating systems
20. Conclusion
Exception Handling in C++ is an essential concept for writing robust, safe, and professional programs. It allows developers to handle runtime errors gracefully without
crashing the application. By using try , throw , and catch , programmers can separate error-handling code from normal logic, making programs easier to debug and maintain. In real-world applications like banking systems, online exams, and payment gateways, exception handling plays a crucial role in ensuring reliability and a smooth user experience. Mastering exception handling is a key step toward becoming a skilled C++ programmer.
Keep practicing — you're doing amazing!
Happy Coding! ![]()