Object Oriented Programming · Unit 10
Exception Handling and File I/O
Exam-focused notes for Exception Handling and File I/O (Object Oriented Programming, BIT153): what the TU syllabus asks and how it has actually been tested, with 15 solved past questions from this unit.
Exception Handling and File I/O in short
This chapter covers how C++ handles run-time errors, how it reads and writes files, and how namespaces and manipulators help organise and format programs.
What this unit covers
- Exception handling definition and purpose
- Try, catch, and throw statements
- Types of exceptions
- Exception handling examples
- Stream definition
- Text file reading and writing
- Binary file reading and writing
- File handling with objects
- Namespace definition
- Stream manipulators: setw and setprecision
Exception handling definition and purpose
2082 · 5 marks
Write a program to handle division by zero exception using try, catch, and throw. [5]
Show solved answerHide answer
Handling Division by Zero Exception Using try, catch, and throw
Concept
In C++, exception handling uses three keywords:
- try - block of code that may throw an exception
- throw - used to throw/raise an exception when an error occurs
- catch - block that handles the thrown exception
Program
#include <iostream>
using namespace std;
// Function to perform division
double divide(int numerator, int denominator) {
if (denominator == 0) {
throw "Division by zero is not allowed!"; // throw exception
}
return (double)numerator / denominator;
}
int main() {
int a, b;
cout << "Enter numerator: ";
cin >> a;
cout << "Enter denominator: ";
cin >> b;
try {
// Code that may cause exception
double result = divide(a, b);
cout << "Result: " << a << " / " << b << " = " << result << endl;
}
catch (const char* msg) {
// Handle the exception
cout << "Exception caught: " << msg << endl;
}
cout << "Program continues after exception handling." << endl;
return 0;
}
Sample Output
Case 1: Normal Division
Enter numerator: 10
Enter denominator: 2
Result: 10 / 2 = 5
Program continues after exception handling.
Case 2: Division by Zero
Enter numerator: 10
Enter denominator: 0
Exception caught: Division by zero is not allowed!
Program continues after exception handling.
Explanation
| Keyword | Role in Program |
|---|---|
throw | Throws a string message when denominator is 0 |
try | Wraps the call to divide() that may fail |
catch | Catches the thrown string and displays the error |
- When denominator is not zero, the division executes normally.
- When denominator is zero,
throwtransfers control directly to thecatchblock, skipping the remainingtryblock. - After the
catchblock executes, the program continues normally, demonstrating graceful error handling.
2081 · 5 marks
Why do we need to handle exception? Illustrate with an example. [5]
2080 · 5 marks
What is exception handling? Explain types of exception handling and explain with suitable example. [5]
Show solved answerHide answer
Exception Handling in C++
What exception handling is
Exception handling is the mechanism by which a C++ program reports a fault at the point where it is detected and deals with it at the point where there is enough context to decide what to do. The detecting code executes throw, which creates an exception object; the runtime then searches outward through the enclosing try blocks for a catch handler whose type matches, destroying every local object it passes on the way. That destruction, called stack unwinding, is what makes the mechanism safe.
The result is a clean split: the ordinary logic stays in the try block and the recovery logic sits in the handlers, instead of an error test being wedged in after every call.
The constructs C++ provides
| Construct | Purpose |
|---|---|
try | Encloses code whose exceptions are to be handled |
catch | Handles one type of exception; several may follow one try |
throw | Raises an exception, or rethrows the current one when written bare |
catch (...) | Catches an exception of any type at all |
noexcept | Promises a function throws nothing, so the compiler may optimise accordingly |
There is deliberately no finally in this list. C++ does not have one, because cleanup belongs in the destructor of the object that owns the resource, and destructors are run automatically during unwinding.
The standard exception hierarchy
Most thrown types derive from std::exception, declared in <exception>, which offers the single member what() returning a description. Two broad families sit under it, in <stdexcept>:
- Logic errors, faults a correct program should have prevented:
std::logic_error, and under itstd::invalid_argument,std::out_of_range,std::domain_error,std::length_error. - Runtime errors, faults only detectable while running:
std::runtime_error, and under itstd::overflow_error,std::underflow_error,std::range_error.
std::bad_alloc from a failed new and std::bad_cast from a failed dynamic_cast on a reference also derive from std::exception. Because they share a base, one handler for const std::exception& can catch the whole family.
Forms exception handling takes
A single try with one handler
#include <iostream>
#include <stdexcept>
int divide(int a, int b) {
if (b == 0)
throw std::runtime_error("division by zero"); // C++ does not throw here by itself
return a / b;
}
int main() {
try {
std::cout << divide(10, 0) << "\n";
} catch (const std::runtime_error& e) {
std::cout << "Error: " << e.what() << "\n";
}
}
Integer division by zero is undefined behaviour in C++, not an automatic exception, so the divisor is tested and the exception thrown on purpose. Anyone coming from Java should note that there is no ArithmeticException here to rely on.
Several handlers on one try
Handlers are tried in order and the first matching one wins, so the most derived type must be written first. A base class handler placed above a derived one would swallow it.
#include <iostream>
#include <vector>
#include <stdexcept>
int main() {
std::vector<int> v{10, 20, 30, 40, 50};
try {
std::cout << v.at(2) << "\n"; // fine
std::cout << v.at(10) << "\n"; // at() checks the index and throws
}
catch (const std::out_of_range& e) { // most derived first
std::cout << "Index error: " << e.what() << "\n";
}
catch (const std::exception& e) { // then the general case
std::cout << "Other error: " << e.what() << "\n";
}
catch (...) { // anything not derived from std::exception
std::cout << "Unknown error\n";
}
}
A raw array subscript is not checked by C++ and throws nothing, so v[10] on a plain array would simply corrupt memory. std::vector::at() performs the bounds test and throws std::out_of_range, which is why it is used here.
Throwing an exception of your own
Deriving from std::runtime_error costs one line and gives the new type a working what().
#include <iostream>
#include <stdexcept>
#include <string>
class NotEligible : public std::runtime_error {
public:
explicit NotEligible(const std::string& msg) : std::runtime_error(msg) {}
};
void checkAge(int age) {
if (age < 18)
throw NotEligible("not eligible to vote");
std::cout << "Eligible to vote\n";
}
int main() {
try {
checkAge(15);
} catch (const NotEligible& e) {
std::cout << "Caught: " << e.what() << "\n";
}
}
Output:
Caught: not eligible to vote
Cleanup, which is where RAII replaces finally
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
class LogFile {
std::ofstream out;
public:
explicit LogFile(const std::string& name) : out(name) {
std::cout << "Log opened\n";
}
~LogFile() { std::cout << "Log closed\n"; } // runs even while an exception propagates
void write(const std::string& s) { out << s << "\n"; }
};
int main() {
try {
LogFile log("run.txt");
log.write("working");
throw std::runtime_error("something failed");
} catch (const std::exception& e) {
std::cout << "Error: " << e.what() << "\n";
}
std::cout << "Program continues\n";
}
Output:
Log opened
Log closed
Error: something failed
Program continues
The destructor of log runs during unwinding, before the handler body, so the resource is released with no cleanup code written at the call site. A std::unique_ptr or a std::lock_guard gives the same guarantee for heap memory and for mutexes.
Points of practice
Catch by const reference, never by value, since catching a base class by value slices away the derived part of the exception object. Order handlers from most derived to most general. Never let an exception escape a destructor, because unwinding while another exception is active calls std::terminate. Throw only for genuinely exceptional conditions, and use a return value or std::optional for outcomes that are expected.
Taken together, try, catch, throw, and the destructors that run during unwinding give C++ a complete error handling mechanism: the fault is reported where it is seen, handled where it can be dealt with, and every resource acquired in between is released on the way out.
2078 · 5 marks
What is exception handling? Explain how to handle an exception with appropriate example. [5]
Show solved answerHide answer
Exception Handling in C++ and How an Exception Is Handled
What exception handling is
Exception handling is the mechanism by which a program signals a fault at the place where it is discovered and deals with it at the place that has enough context to decide what to do. An exception is an unexpected condition that arises while the program runs, such as a file that will not open, memory that cannot be allocated, or an argument that makes an operation meaningless, and which would otherwise leave the program with no sensible way to continue.
In C++ the mechanism has three parts. Code that detects the fault executes throw, which creates an exception object. The runtime then searches outward through the enclosing try blocks for a catch handler whose type matches that object. On the way out it destroys every local object created since the try block was entered, in reverse order of construction. That destruction is called stack unwinding, and it is what makes the whole thing safe to use.
The constructs involved
| Construct | Purpose |
|---|---|
try | Encloses the code whose exceptions are to be handled |
catch | Handles one type of exception; several may follow one try |
throw | Raises an exception; written bare inside a handler it rethrows the current one |
catch (...) | Catches an exception of any type whatsoever |
| Destructors | Run automatically during unwinding and perform the cleanup |
Notice what is missing. C++ has no finally block, because it does not need one: cleanup goes into the destructor of the object that owns the resource, and that destructor is guaranteed to run whether the block is left normally or through an exception. The idiom is called RAII, resource acquisition is initialisation.
Most thrown types derive from std::exception, whose member what() returns a description. <stdexcept> supplies the usual ones, std::runtime_error, std::out_of_range, std::invalid_argument among them, so a single handler for const std::exception& can cover the whole family.
The flow when an exception is thrown
The statements in the try block run in order. If none of them throws, every handler is skipped and execution continues after the last one. If one of them throws, the rest of the try block is abandoned, the local objects built so far are destroyed, and the handlers are examined top to bottom until one whose type matches is found. That handler runs, and execution then resumes after the last handler, not back inside the try block. If no handler in the whole program matches, std::terminate is called and the program aborts.
Worked example
Integer division by zero is undefined behaviour in C++, not an automatic exception, so unlike Java there is nothing to catch unless the divisor is tested and the exception thrown deliberately.
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
// RAII, so cleanup happens without a finally block.
class LogFile {
std::ofstream out;
public:
explicit LogFile(const std::string& name) : out(name) {
std::cout << "Log opened\n";
}
~LogFile() { std::cout << "Log closed, resources released\n"; }
void write(const std::string& msg) { out << msg << "\n"; }
};
int divide(int a, int b) {
if (b == 0)
throw std::runtime_error("cannot divide by zero"); // raised on purpose
return a / b;
}
int main() {
int a = 10, b = 0;
try {
LogFile log("run.txt"); // acquired inside the try block
log.write("starting division");
std::cout << "Result: " << divide(a, b) << "\n";
std::cout << "This line is never reached\n";
}
catch (const std::runtime_error& e) { // caught by const reference
std::cout << "Exception caught: " << e.what() << "\n";
}
catch (const std::exception& e) { // broader net, written after the narrower one
std::cout << "Other failure: " << e.what() << "\n";
}
std::cout << "Program continues normally.\n";
return 0;
}
Output:
Log opened
Log closed, resources released
Exception caught: cannot divide by zero
Program continues normally.
What the example shows
divide checks its divisor and throws std::runtime_error when it is zero, since C++ would otherwise walk straight into undefined behaviour. The try block is abandoned at that point, so the "never reached" line does not print. Before the handler is entered, the LogFile object created inside the block is destroyed, which is why the closing message appears first in the output: the file is already closed by the time the error is reported, and not one line of cleanup code had to be written at the call site.
The handler prints the description carried by the exception through e.what(). Handlers are ordered from the most derived type to the most general, because the first match wins and a base class handler written first would swallow everything. Each one takes its argument by const reference, since catching by value would slice the derived part off the exception object.
Because the exception was handled, the program does not abort. Execution resumes after the last handler and the final line prints normally.
Why this matters
Exception handling keeps a fault from ending the process, reports the reason in terms a user can act on, and keeps the success path free of an error test after every call. Combined with destructors that release what they acquired, it also guarantees that files, locks, and memory are given back on the failure path as reliably as on the normal one.
0 · 5 marks
Write a program to handle "array index out of range" exception. [5]
Text file reading and writing
2082 · 5 marks
Write a C++ program to read a text file named data.txt and display its contents on the screen. Also, count the number of lines, words, and characters in the file and display these counts after showing the file content. [5]
2079 · 5 marks
Define stream. How do you read the text from file? Describe. [5]
2078 · 5 marks
Write a program that writes the contents of file 1 into file 2. [5]
0 · 5 marks
Write a program to read text from keyboard and write it to a file named "test.txt". Again read the content of file and display it in the monitor. [5]
Binary file reading and writing
2081 · 10 marks
Define stream.How do you read and write binary files?Write a program to read an integer from the user and if the integer is less than 100 then write it in file named "SMALL.TXT" otherwise write in file named "LARGE.TXT".[2+3+5]
Show solved answerHide answer
Streams, Binary File I/O, and File Writing Program
1. Definition of Stream (2 marks)
A stream is an abstraction that represents a flow of data between a program and an input/output device (such as a keyboard, monitor, disk file, etc.).
- A stream acts as a logical interface between the program and the actual I/O device.
- In C++, streams are implemented through a hierarchy of classes defined in headers like
<iostream>and<fstream>. - There are two main types:
- Input Stream: Data flows into the program (e.g., reading from a file or keyboard).
- Output Stream: Data flows out of the program (e.g., writing to a file or screen).
Key stream classes:
ifstream(input file stream),ofstream(output file stream),fstream(both input and output).
2. Reading and Writing Binary Files (3 marks)
Binary files store data in the same format as it is stored in memory (raw bytes), unlike text files which store data as readable characters.
Opening a Binary File
Use the ios::binary flag along with the file mode:
ifstream fin("file.dat", ios::in | ios::binary); // reading
ofstream fout("file.dat", ios::out | ios::binary); // writing
Writing to a Binary File
Use the write() member function:
fout.write((char*) &variable, sizeof(variable));
- The first argument is a pointer to the data cast to
char*. - The second argument is the number of bytes to write.
Reading from a Binary File
Use the read() member function:
fin.read((char*) &variable, sizeof(variable));
Example
#include <fstream>
using namespace std;
int main() {
int num = 42;
// Write binary
ofstream fout("data.bin", ios::out | ios::binary);
fout.write((char*) &num, sizeof(num));
fout.close();
// Read binary
int readNum;
ifstream fin("data.bin", ios::in | ios::binary);
fin.read((char*) &readNum, sizeof(readNum));
fin.close();
return 0;
}
3. Program: Write Integer to SMALL.TXT or LARGE.TXT (5 marks)
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int num;
// Read integer from user
cout << "Enter an integer: ";
cin >> num;
if (num < 100) {
// Write to SMALL.TXT
ofstream fout("SMALL.TXT", ios::app); // ios::app to append
if (!fout) {
cout << "Error opening SMALL.TXT!" << endl;
return 1;
}
fout << num << endl;
fout.close();
cout << num << " has been written to SMALL.TXT" << endl;
} else {
// Write to LARGE.TXT
ofstream fout("LARGE.TXT", ios::app); // ios::app to append
if (!fout) {
cout << "Error opening LARGE.TXT!" << endl;
return 1;
}
fout << num << endl;
fout.close();
cout << num << " has been written to LARGE.TXT" << endl;
}
return 0;
}
Sample Output
Enter an integer: 45
45 has been written to SMALL.TXT
Enter an integer: 250
250 has been written to LARGE.TXT
Explanation of Key Steps
| Step | Description |
|---|---|
cin >> num | Reads integer from the user |
if (num < 100) | Checks the condition |
ofstream fout("SMALL.TXT", ios::app) | Opens SMALL.TXT in append mode |
ofstream fout("LARGE.TXT", ios::app) | Opens LARGE.TXT in append mode |
if (!fout) | Checks if file opened successfully |
fout << num | Writes the integer to the file |
fout.close() | Closes the file after writing |
Note:
ios::app(append mode) is used so that previously written values are not overwritten each time the program runs. You may also useios::outif overwriting is acceptable.
2080.1 · 5 marks
Write a program that writes objects to a binary file and reads objects from the same file. [5]
Stream manipulators
2081 · 5 marks
Illustrate the use of set w and set precision with example. [5]
File handling with objects
2080 · 5 marks
Write a Program to read and write values through object using File Handling. [5]
Namespace definition
2079 · 5 marks
Define namespace. List any two manipulators with their uses. [5]
Try, catch, and throw statements
2080.1 · 5 marks
Illustrate Exception handling in C++ using try, throw and catch statements. [5]
Make Unit 10 stick
Practice BIT153 with flashcards & quizzes