Exception Handling
Exception Handling is a mechanism that allows a program to detect and
handle runtime errors gracefully — without crashing.
It helps maintain normal program flow even when unexpected situations
occur.
Common Runtime Errors
Examples of runtime errors:
Division by zero
File not found
Invalid input
Memory allocation failure
Array index out of bounds
Keywords Used in Exception Handling
Keyword Purpose
try Defines a block of code to test for errors
throw Used to signal (raise) an exception
catch Defines a block of code that handles the exception
try-catch Combined, they form an exception handling mechanism
Basic Syntax
try {
// Code that might throw an exception
throw <expression>;
}
catch (<exception_type> <variable>) {
// Code to handle the exception
}
Example 1: Simple Division Program
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter numerator and denominator: ";
cin >> a >> b;
try {
if (b == 0)
throw "Division by zero error!";
cout << "Result: " << (float)a / b << endl;
}
catch (const char* msg) {
cout << "Exception caught: " << msg << endl;
}
cout << "Program continues..." << endl;
return 0;
}
Multiple Catch Blocks
You can have more than one catch block to handle different types of
exceptions.
#include <iostream>
using namespace std;
int main() {
try {
int x;
cout << "Enter a number: ";
cin >> x;
if (x == 0)
throw 0; // throw int
else if (x == 1)
throw 'A'; // throw char
else if (x == 2)
throw string("Error code 2"); // throw string
cout << "No exception occurred." << endl;
}
catch (int e) {
cout << "Integer exception caught: " << e << endl;
}
catch (char e) {
cout << "Character exception caught: " << e << endl;
}
catch (string &e) {
cout << "String exception caught: " << e << endl;
}
return 0;
}
Catch-All Handler
To catch any type of exception, use a catch-all handler:
catch (...) {
cout << "Unknown exception caught!" << endl;
}
Exception Handling in Classes
You can also throw and catch exceptions inside classes or member
functions.
#include <iostream>
using namespace std;
class Divide {
public:
double division(int a, int b) {
if (b == 0)
throw string("Division by zero!");
return (double)a / b;
}
};
int main() {
Divide d;
int x, y;
cout << "Enter two numbers: ";
cin >> x >> y;
try {
cout << "Result: " << [Link](x, y) << endl;
}
catch (string &err) {
cout << "Exception caught: " << err << endl;
}
return 0;
}
User-Defined Exceptions (Custom Exception Class)
You can create your own exception classes for specific error types.
#include <iostream>
using namespace std;
class DivideByZero {
public:
const char* what() {
return "Error: Division by zero!";
}
};
int main() {
int a, b;
cout << "Enter numerator and denominator: ";
cin >> a >> b;
try {
if (b == 0)
throw DivideByZero();
cout << "Result: " << (float)a / b << endl;
}
catch (DivideByZero &e) {
cout << [Link]() << endl;
}
return 0;
}
Re-throwing Exceptions
Sometimes you may catch an exception and then rethrow it to a higher
level.
try {
try {
throw 100;
}
catch (int n) {
cout << "Caught inside inner try: " << n << endl;
throw; // rethrow
}
}
catch (int n) {
cout << "Caught in outer try: " << n << endl;
}
Standard Exceptions (from <exception> library)
C++ provides several built-in exception classes, such as:
Exception Description
std::exception Base class for all exceptions
std::bad_alloc Thrown by new when memory allocation fails
std::out_of_range Thrown when accessing outside a container’s range
std::runtime_error Generic runtime error
#include <iostream>
#include <exception>
using namespace std;
int main() {
try {
int* p = new int[100000000000]; // too large
}
catch (bad_alloc &e) {
cout << "Exception: " << [Link]() << endl;
}
}
1. Write a program that takes two integers from the user and
performs division. Throw an exception if the divisor is zero.
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
int a, b;
cout << "Enter dividend: ";
cin >> a;
cout << "Enter divisor: ";
cin >> b;
try {
if (b == 0)
throw runtime_error("Division by zero error!");
cout << "Result = " << a / b << endl;
} catch (runtime_error &e) {
cout << "Caught exception: " << [Link]() << endl;
}
return 0;
}
2. Ask the user to enter their age. If the age is negative or
greater than 150, throw an exception. Catch it and display a
proper message.
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
try {
if (age < 0 || age > 150)
throw out_of_range("Invalid age entered!");
cout << "Your age is: " << age << endl;
} catch (out_of_range &e) {
cout << "Caught exception: " << [Link]() << endl;
}
return 0;
}
3. Create an array of 5 integers. Ask the user to input an index.
Throw an exception if the index is out of bounds and catch it.
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int index;
cout << "Enter index (0-4): ";
cin >> index;
try {
if (index < 0 || index >= 5)
throw out_of_range("Index out of bounds!");
cout << "Value at index " << index << " is " <<
arr[index] << endl;
} catch (out_of_range &e) {
cout << "Caught exception: " << [Link]() << endl;
}
return 0;
}
4. Simulate a bank account with deposit and withdraw functions.
Throw an exception if the user tries to withdraw more than the
balance.
#include <iostream>
#include <stdexcept>
using namespace std;
class BankAccount {
double balance;
public:
BankAccount(double b) : balance(b) {}
void deposit(double amount) { balance += amount; }
void withdraw(double amount) {
if (amount > balance)
throw runtime_error("Insufficient balance!");
balance -= amount;
}
double getBalance() { return balance; }
};
int main() {
BankAccount account(1000);
double amount;
cout << "Enter amount to withdraw: ";
cin >> amount;
try {
[Link](amount);
cout << "Withdrawal successful. Remaining balance: "
<< [Link]() << endl;
} catch (runtime_error &e) {
cout << "Caught exception: " << [Link]() << endl;
}
return 0;
}
5. Try to open a file for reading. Throw an exception if the file
cannot be opened, and handle it by displaying an error message.
#include <iostream>
#include <fstream>
#include <stdexcept>
using namespace std;
int main() {
ifstream file("[Link]");
try {
if (!file.is_open())
throw runtime_error("File could not be opened!");
cout << "File opened successfully." << endl;
[Link]();
} catch (runtime_error &e) {
cout << "Caught exception: " << [Link]() << endl;
}
return 0;
}
6. Ask the user to input the temperature. If it’s below -273°C,
throw an exception for invalid temperature.
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
double temp;
cout << "Enter temperature in Celsius: ";
cin >> temp;
try {
if (temp < -273)
throw runtime_error("Temperature below absolute
zero is impossible!");
cout << "Temperature is: " << temp << "°C" << endl;
} catch (runtime_error &e) {
cout << "Caught exception: " << [Link]() << endl;
}
return 0;
}
7. Ask the user to enter a string. Throw an exception if the string
length exceeds 20 characters.
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
try {
if ([Link]() > 20)
throw length_error("String length exceeds 20
characters!");
cout << "Your string: " << str << endl;
} catch (length_error &e) {
cout << "Caught exception: " << [Link]() << endl;
}
return 0;
}
8. Write a function to calculate the square root of a number.
Throw an exception if the number is negative.
#include <iostream>
#include <cmath>
#include <stdexcept>
using namespace std;
double safeSqrt(double num) {
if (num < 0)
throw runtime_error("Cannot calculate square root of
negative number!");
return sqrt(num);
}
int main() {
double num;
cout << "Enter a number: ";
cin >> num;
try {
cout << "Square root = " << safeSqrt(num) << endl;
} catch (runtime_error &e) {
cout << "Caught exception: " << [Link]() << endl;
}
return 0;
}
9. Create a custom exception class InvalidScoreException. Take a
score input from the user and throw this exception if the score is
not between 0 and 100.
#include <iostream>
#include <stdexcept>
using namespace std;
class InvalidScoreException : public exception {
public:
const char* what() const noexcept override {
return "Score must be between 0 and 100!";
}
};
int main() {
int score;
cout << "Enter your score: ";
cin >> score;
try {
if (score < 0 || score > 100)
throw InvalidScoreException();
cout << "Your score: " << score << endl;
} catch (InvalidScoreException &e) {
cout << "Caught exception: " << [Link]() << endl;
}
return 0;
}
10. Write a program that takes two numbers from the user.
Throw an exception if the first number is negative.
Throw a different exception if the second number is zero.
Handle both exceptions in separate catch blocks.
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
int a, b;
cout << "Enter first number: ";
cin >> a;
cout << "Enter second number: ";
cin >> b;
try {
if (a < 0)
throw runtime_error("First number cannot be
negative!");
if (b == 0)
throw runtime_error("Second number cannot be
zero!");
cout << "Numbers are valid: " << a << ", " << b <<
endl;
} catch (runtime_error &e) {
cout << "Caught exception: " << [Link]() << endl;
}
return 0;
}