1. Introduction to Exception Handling
Exception handling is a mechanism in C++ used to handle runtime errors (also
called exceptional conditions) in a structured, controlled, and maintainable way.
Runtime errors occur during program execution, such as division by zero, file not
found, memory allocation failure, or invalid user input.
In traditional programming, errors were handled using conditional statements (if-
else). However, this approach makes programs lengthy, less readable, and
difficult to maintain. Exception handling separates normal program logic from
error-handling logic, improving readability, reliability, and robustness.
Exception handling allows a program to continue execution or terminate gracefully
instead of crashing abruptly.
C++ provides three main keywords for exception handling:
Try
Throw
catch
2. Basic Exception Handling Model in C++
2.1 try Block
The try block contains code that may generate an exception. It encloses statements that
need monitoring for runtime errors.
If an exception occurs inside the try block, normal execution stops, and control is
transferred to the appropriate catch block.
2.2 throw Statement
The throw statement is used to signal the occurrence of an exception. It throws an
object (usually a value or class object) that represents the error.
2.3 catch Block
The catch block handles the exception thrown by the throw statement. Each catch block
specifies the type of exception it can handle.
3. Flow of Control in Exception Handling
3.1 Normal Flow of Control
, When no exception occurs:
Statements inside the try block execute sequentially.
All catch blocks are skipped.
Program continues execution after the try-catch structure.
3.2 Flow of Control When Exception Occurs
When an exception is thrown:
Execution inside the try block stops immediately.
Control is transferred to the matching catch block.
Stack unwinding begins (local objects are destroyed).
After the catch block executes, control moves to the statement after the try-catch
structure.
This mechanism is known as exception propagation.
3.3 Program Example: Flow of Control:
Write a C++ program to demonstrate exception handling by handling division
by zero using try, throw, and catch.
#include <iostream>
using namespace std;
int main() {
try {
int a = 10; // Numerator
int b = 0; // Denominator (0 causes division by zero)
// Check if denominator is zero
if (b == 0)
throw "Division by zero error"; // Throw exception
// This statement will not execute if exception is thrown
cout << "Result = " << a / b << endl;
}
catch (const char* msg) { // Catch block to handle exception
cout << "Exception caught: " << msg << endl;
}
// Program continues after handling exception
cout << "Program continues normally." << endl;
return 0; // End of program
}
Explanation: