EXCEPTION AND EXCEPTION
HANDLING IN C++
MODULE 5
CONTENTS
Exception Handling:
• Introduction to Exception
• Benefits of Exception handling
• Try and catch block, Throw statement
• Pre-defined exceptions in C++
2
EXCEPTION
• The term "exception" in programming refers to an unexpected event or error that
occurs during the execution of a program, disrupting its normal flow.
• Exception is a runtime error.
• Types of Exception:
1. Synchronous Exceptions
2. Asynchronous Exceptions
3
EXCEPTION
1. Synchronous Exception:
• Exception Occurred due to logical errors or invalid operations during program
execution.
• Examples:
• Division by zero
• Array index out of bounds
• File not found
• In C++ exception handling mechanism is designed to handle only synchronous
exceptions.
4
EXCEPTION
2. Asynchronous Exceptions:
• Caused by external events unrelated to program flow.
• Examples:
• Hardware failure
• Power Failure
• User interruption
• Segmentation fault
• Out of Memory
• Asynchronous Exceptions cannot be handled by C++ exception handling mechanism.
5
EXCEPTION HANDLING
Exception Handling is a mechanism in programming used to handle runtime errors,
allowing the program to continue its execution instead of crashing. It separates error-
handling code from regular code, making programs more readable and robust.
• Mechanism of Exception Handling:
Find the problem( hit the Exception)
Inform the an error has occurred( throw the Exception)
Receive the error information ( catch the Exception)
Take corrective actions ( handle the exception)
6
EXCEPTION HANDLING
Exception in C++ is handled using the three keywords:
• try
• throw
• catch
7
EXCEPTION HANDLING
try block – block of statements which detects exception and throws the
exception (if detected).
• Syntax:
try
{
……………
throws exception;
…………….
…………….
}
8
EXCEPTION HANDLING
throw statement – When an exception is detected in the try block, then the
exception is thrown using the throw keyword
• Syntax:
try
{
……………
throws exception;
…………….
…………….
}
9
EXCEPTION HANDLING
catch block – block of statements which catches the exception thrown by
the throw statement in the try block and handles it appropriately.
• Syntax:
catch( type arg)
{
…………….
…………….
…………….
…………….
}
10
EXCEPTION HANDLING
Program for Division by Zero: try {
Program: if ((a - b) != 0)
#include <iostream> {
d = c / (a - b);
using namespace std;
cout << "Result is: " << d << endl;
int main() { }
int a, b, c; else{
float d; // Throw an exception if division by zero is about to occur
cout << "Enter the value of a: "; throw "Division by zero error!";
}
cin >> a;
}
cout << "Enter the value of b: "; catch (char* msg) {
cin >> b; // This catches exceptions thrown as a char* (string
cout << "Enter the value of c: "; exceptions), such as: throw “Division by zero error!“.
cout << "Error: " << msg << endl;
cin >> c;
}
return 0;
} 11
EXCEPTION HANDLING
• char* msg is used to catch raw string errors thrown like throw "error".
• Raw string are C-style string literals or char* pointers
• It's outdated and error-prone.
• Use std::exception and its subclasses in modern C++ that are pre-defined in the headerfile
<stdexcept>
12
EXCEPTION HANDLING
Program for Array Index out of Bounds:
Program:
#include <iostream>
#include <stdexcept>
using namespace std;
int getValueAtIndex(int arr[], int index, int size)
{
if (index < 0 || index >= size)
{
throw out_of_range("Index out of bounds");
}
return arr[index];
}
13
EXCEPTION HANDLING
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int index;
cout << "Enter an index to access the array: ";
cin >> index;
try
{
int value = getValueAtIndex(arr, index, size);
cout << "Value at index " << index << " is: " << value << endl;
}
catch (const out_of_range& e)
{
cout << "Exception caught: " << [Link]() << endl;
}
return 0; 14
}
EXCEPTION HANDLING
Explanation:
• out_of_range: A standard C++ exception class, derived from std::logic_error, used when you
try to access an element outside the valid range (e.g., accessing a vector
element at an invalid index).
• out_of_range& e: Catch the exception by const reference. This avoids copying the exception
object that is “e” and preserves polymorphism.
• [Link](): Returns a const char* message describing the exception. This is part of the
std::exception interface.
15
EXCEPTION HANDLING
Multiple catch blocks: Multiple catch blocks allow a program to handle different types of exceptions
thrown from a single try block. Each catch block is designed to handle a specific type of exception.
Syntax:
try {
// Code that may throw different types of exceptions
}
catch (int e) {
// Handle integer exceptions
}
catch (const char* msg) {
// Handle string exceptions
}
catch (...) {
// Handle any other type of exception (generic catch)
}
16
EXCEPTION HANDLING
Example:
Q. Write a C++ program to compute the roots of a quadratic equation of
the form ax² + bx + c = 0.
• If the roots are real and unequal, display them.
• If the roots are equal, throw and handle a logic_error exception with the message "Roots are
equal".
• If the roots are imaginary, throw and handle a runtime_error exception with the message
"Imaginary roots - cannot compute".
• Use appropriate try, catch, and throw statements to handle exceptions.
17
EXCEPTION HANDLING
PROGRAM:
#include <iostream>
#include <cmath>
#include <stdexcept>
using namespace std;
// Function to find and display real & unequal roots
void findRoots(double a, double b, double c)
{
double discriminant = b * b - 4 * a * c;
if (discriminant < 0)
throw runtime_error("Imaginary roots - cannot compute");
else if (discriminant == 0)
throw logic_error("Roots are equal");
else {
double root1 = (-b + sqrt(discriminant)) / (2 * a);
double root2 = (-b - sqrt(discriminant)) / (2 * a);
cout << "Roots are real and unequal: " << root1 << " and " << root2 << endl;
}
}
18
EXCEPTION HANDLING
int main() {
double a, b, c;
cout << "Enter coefficients a, b, and c: ";
cin >> a >> b >> c;
try {
findRoots(a, b, c);
}
catch (const logic_error &e) {
cout << "Exception: " << [Link]() << endl;
}
catch (const runtime_error &e) {
cout << "Exception: " << [Link]() << endl;
}
return 0;
} 19
BENEFITS OF EXCEPTION HANDLING
1. Separation of Error Handling from Normal Logic
• Keeps your main code clean and focused on its core task.
• Error-handling logic is separated into try-catch blocks.
2. Improved Code Readability and Maintainability
• Avoids deeply nested if statements for error checking.
• Makes code easier to understand and debug.
3. Centralized Error Handling
• One can handle multiple errors in one place.
• Makes it easy to log, report, or recover from different error types.
4. Type-Safe and Hierarchical
• Catch exceptions by base type (std::exception) or derived type (e.g., std::out_of_range).
20
BENEFITS OF EXCEPTION HANDLING
5. Supports Stack Unwinding
• When an exception is thrown, C++ automatically calls destructors for all local objects in scope.
• Ensures proper cleanup of resources (memory, file handles, etc.).
6. Flexible Recovery Mechanism
• We can choose to retry, log, propagate, or gracefully exit depending on the exception.
7. Propagates Errors Across Function Calls
• Exceptions can be thrown in one function and caught in another, without needing to pass error
codes manually.
21
PREDEFINED EXCEPTION
Predefined exceptions in C++ are part of the Standard Library (specifically from the <stdexcept>
header). They are ready-to-use exception classes derived from the base class std::exception.
Types:
1. std::invalid_argument: Thrown when a function receives an invalid argument.
2. std::out_of_range: Thrown when accessing an element outside the valid range.
3. std::overflow_error / std::underflow_error: Thrown when arithmetic operation results in overflow or
underflow.
4. std::length_error: It is thrown to indicate that a length-related operation exceeded the
maximum allowed size of a container or object.
22