Task 1: Basic Exception Handling for Input Validation
1. What is Exception Handling?
Exception handling is a mechanism that enables programs to deal with unexpected situations or
errors during runtime, such as invalid input, division by zero, or file operation errors. It provides
a structured way to handle errors, ensuring that the program doesn't crash and can continue
execution or terminate gracefully.
2. Importance of Exception Handling in Input Validation
Input validation is the process of ensuring that user-provided data is:
• Correct in type (e.g., integer, float, string).
• Within acceptable ranges (e.g., age > 0, marks ≤ 100).
• Free from invalid or harmful inputs.
Without proper input validation, the program might behave unpredictably, leading to runtime
errors or security vulnerabilities.
Exception handling simplifies input validation by catching and managing errors when invalid
data is entered.
Key Concepts of Exception Handling
1. Exceptions: An exception is an event that disrupts the normal flow of a program's
execution. It can occur due to various reasons, such as invalid input, division by zero, or
resource unavailability.
2. The Three Keywords: In C++, exception handling is built around three main keywords:
• try: This block contains code that may throw an exception. If an exception occurs,
control is transferred to the corresponding catch block.
• throw: This keyword is used to signal that an exceptional condition has occurred.
When a throw statement is executed, it creates an exception object and transfers
control to the catch block.
• catch: This block handles the exception thrown by the try block. It defines how to
respond to specific types of exceptions.
• Write and run this code
int main() {
int number;
try {
cout << "Enter a positive integer: ";
cin >> number;
// Check if input is valid
if (cin.fail()) {
throw "Invalid input! Please enter an integer.";
}
// Check for positive number
if (number <= 0) {
throw "Only positive integers are allowed!";
}
cout << "You entered: " << number << endl;
}
catch (const char* errorMsg) {
cerr << "Error: " << errorMsg << endl;
}
return 0;
Advantages of Exception Handling
• Exception handling separates error management from regular code flow, making
programs easier to read and maintain. Traditional error handling often involves cluttering
code with numerous if-else statements.
• Functions can choose which exceptions to handle internally and which ones to propagate
up to their callers. This allows for more granular control over error management.
• By using exceptions, developers can create programs that are more resilient to
unexpected conditions without crashing.
Activity: Add exception handling functionality in your ATM program
Task 2: File Handling for Reading and Writing Data
1. What is File Handling?
File handling refers to performing operations on files, such as creating, opening, reading, writing,
and closing files.
It allows programs to store data persistently, even after the program terminates.
2. Why File Handling?
1. Enables storing data for long-term use.
2. Allows exporting data for use by other applications or users.
3. Facilitates handling large datasets that cannot fit into memory.
3. File Handling in C++
C++ provides file handling through the <fstream> library, which includes three primary classes:
1. ofstream: For writing to files.
2. ifstream: For reading from files.
3. fstream: For both reading and writing.
4. Basic File Operations
4.1 Writing Data to a File
To write data to a file:
1. Create an ofstream object.
2. Use the open() method to open the file (or open the file during object creation).
3. Write data using the insertion operator (<<).
4. Close the file using the close() method.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("example.txt"); // Open file for writing
if (outFile.is_open()) {
outFile << "Hello, World!\n";
outFile << "Welcome to file handling in C++.\n";
outFile.close(); // Close file
cout << "Data written to file successfully.\n";
} else {
cerr << "Error opening file for writing.\n";
return 0;
NB: Notice where the file “example.txt” is stored!
4.2 Reading Data from a File
To read data from a file:
1. Create an ifstream object.
2. Open the file using the open() method or during object creation.
3. Read data using the extraction operator (>>) or getline() for strings.
4. Close the file after reading
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream inFile("example.txt"); // Open file for reading
string line;
if (inFile.is_open()) {
while (getline(inFile, line)) { // Read line by line
cout << line << endl; // Print the line
}
inFile.close(); // Close file
} else {
cerr << "Error opening file for reading.\n";
}
return 0;
}
4.3 Reading and Writing with fstream
The fstream class allows both reading and writing in a single object.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream file("example.txt", ios::in | ios::out | ios::app); // Open for reading and
appending
if (file.is_open()) {
// Write data
file << "Adding more lines.\n";
// Move to the beginning for reading
file.seekg(0, ios::beg);
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close();
} else {
cerr << "Error opening file.\n";
}
return 0;
}
What is ios?
• ios stands for input/output stream, a base class in C++ that defines constants (flags) for
file operations.
• The ios namespace provides several flags that specify how a file should be opened or
operated on.
Open Mode Flags Used:
1. ios::in
o Opens the file for input (reading).
o Without this flag, reading operations like getline() or >> would fail.
2. ios::out
o Opens the file for output (writing).
o If the file does not exist, it is created.
o By itself, this flag overwrites the content of the file, but when combined with
ios::app, it preserves the content and appends new data.
3. ios::app
o Opens the file in append mode, which positions the file pointer at the end of the
file.
o Writing operations will always add content at the end of the file, preserving the
existing content.
5. Error Handling in File Operations
It’s essential to handle errors, such as:
• File not found.
• Insufficient permissions.
• End of file reached.
Common Methods:
1. is_open(): Checks if the file is successfully opened.
2. eof(): Checks if the end of the file is reached.
3. fail(): Indicates a logical error in file operations.
Hands-On Activities
1. Write a program to save user details (name, age, email) to a file.
2. Read the saved details from the file and display them.
3. Implement a basic text editor that can read from and write to a file.