Sometimes a program faces a problem while it is running. For example, a user may try to divide a number by zero or enter an invalid value. Instead of letting the program stop suddenly, C++ provides exception handling. C++ Exception Handling helps us find and handle errors while the program is running.
What is C++ Exception Handling?
An exception is a problem that happens while a program is running.
For example:
10 ÷ 0
Division by zero is not a valid operation. We can use exception handling to deal with such problems. C++ mainly uses three keywords:
trycatchthrow
Let’s understand them one by one.
try
The try block contains code that might cause a problem.
try {
// Code that might cause an exception
}
For example:
#include <iostream>
using namespace std;
int main() {
try {
int age = -1;
if (age < 0) {
throw age;
}
}
return 0;
}
Here, throw creates an exception.
But we also need a catch block to handle it.
throw
The throw keyword is used to send an exception.
throw value;
For example:
throw age;
This tells C++ that something went wrong and sends the value to a catch block.
catch
The catch block handles the exception.
A simple example:
#include <iostream>
using namespace std;
int main() {
try {
int age = -1;
if (age < 0) {
throw age;
}
}
catch (int value) {
cout << "Invalid age: " << value;
}
return 0;
}
Output:
Invalid age: -1
Here is what happened:
try
↓
Problem found
↓
throw
↓
catch
↓
Error handled
A Simple Example
Let’s check whether a number is zero.
#include <iostream>
using namespace std;
int main() {
int number = 0;
try {
if (number == 0) {
throw number;
}
cout << "Number is not zero.";
}
catch (int value) {
cout << "Error: Number cannot be zero.";
}
return 0;
}
Output:
Error: Number cannot be zero.
The program doesn’t suddenly stop. The problem is caught and handled.
C++ Multiple catch Blocks
Sometimes different types of errors can happen.
C++ allows us to use more than one catch block.
#include <iostream>
using namespace std;
int main() {
try {
throw 10;
}
catch (int value) {
cout << "Integer exception: " << value;
}
catch (double value) {
cout << "Double exception: " << value;
}
return 0;
}
Output:
Integer exception: 10
C++ checks the catch blocks and uses the one that matches the type of the exception.
For example:
throw 10;
throws an int, so:
catch (int value)
handles it.
Catching Different Types
We can throw different types of values.
#include <iostream>
using namespace std;
int main() {
try {
throw "Something went wrong";
}
catch (const char* message) {
cout << message;
}
return 0;
}
Output:
Something went wrong
Here, the text is caught using:
catch (const char* message)
C++ Exception Handling Example
Let’s create a small program that checks a person’s age.
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
try {
if (age < 0) {
throw age;
}
cout << "Your age is " << age;
}
catch (int value) {
cout << "Invalid age entered.";
}
return 0;
}
If the user enters:
14
Output:
Enter your age: 14
Your age is 14
If the user enters:
-5
Output:
Enter your age: -5
Invalid age entered.
The try block checks the value, throw reports the problem, and catch handles it.
Why Use Exception Handling in C++?
Exception handling is useful because it helps programs deal with unexpected situations.
For example:
- Invalid input
- File errors
- Calculation errors
- Problems while working with resources
It can make programs more reliable and easier to manage.
Key Points to Remember
- An exception is a problem that happens while a program is running.
trycontains code that may cause an exception.throwis used to report an exception.catchhandles the exception.- You can use multiple
catchblocks. - The type of the exception should match the
catchblock.
Mini Quiz
Mini Project
Mini Project: ATM Withdrawal Checker
Question:
Write a C++ program that uses exception handling to handle invalid ATM withdrawal requests.
- Ask the user to enter their account balance.
- Ask the user to enter the withdrawal amount.
- Use a
tryblock to check the withdrawal amount. - Use
throwif the withdrawal amount is less than or equal to0. - Use
throwif the withdrawal amount is greater than the available balance. - Use
catchblocks to handle the errors. - If the withdrawal is valid, subtract the amount from the balance.
- Display the remaining balance.
View Answer Code
#include <iostream>
using namespace std;
int main() {
double balance, amount;
cout << "Enter account balance: ";
cin >> balance;
cout << "Enter withdrawal amount: ";
cin >> amount;
try {
if (amount <= 0) {
throw amount;
}
if (amount > balance) {
throw "Insufficient balance.";
}
balance -= amount;
cout << "Withdrawal successful.\n";
cout << "Remaining balance: " << balance;
}
catch (double value) {
cout << "Invalid withdrawal amount: " << value;
}
catch (const char* message) {
cout << message;
}
return 0;
}
What’s Next?
In the next chapter, we will learn about C++ File Handling and see how to create, write, read, and work with files using C++.
Frequently Asked Questions (FAQs)
Q1. What is exception handling in C++?
Exception handling in C++ is a way to detect and handle problems that occur while a program is running.
Q2. How does try and catch work in C++?
The try block contains code that may cause an exception, while the catch block handles the exception when one is thrown.
Q3. What is the use of throw in C++?
The throw keyword is used to report or send an exception from the try block to a matching catch block.
Q4. Can C++ have multiple catch blocks?
Yes. C++ allows multiple catch blocks so different types of exceptions can be handled separately.
Q5. What is the difference between throw and catch in C++?
throw sends an exception when a problem occurs, while catch receives and handles that exception.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
