10 Exception Handling And File I O

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.

Exception Handling and File I/O: notes

Exception handling definition and purpose

An exception is an error that happens while the program runs, such as dividing by zero or running out of memory. Exception handling is a way to detect these errors and deal with them without crashing the program.

Purposes:

  • It separates error-handling code from normal code.
  • It stops the program from ending suddenly.
  • An error can be passed up from the place where it happens to the place that can handle it.
  • It makes programs more reliable.

C++ uses three keywords: try, throw and catch.

Try, catch, and throw statements

  • try: a block that holds code that may cause an exception.
  • throw: raises an exception with a value.
  • catch: a block that handles the exception.
int main() {
    int a = 10, b = 0;
    try {
        if (b == 0) throw "Division by zero";
        cout << a / b;
    }
    catch (const char *msg) {
        cout << "Error: " << msg;
    }
    cout << "\nProgram continues";
}

When throw runs, control leaves the try block at once and goes to the matching catch. After the catch finishes, the program continues after it.

Types of exceptions

Exceptions can be of any type. The catch block is chosen by the type thrown.

try {
    int x = -1;
    if (x < 0) throw x;           // int
    // throw 2.5;                 // double
}
catch (int e)    { cout << "int " << e; }
catch (double e) { cout << "double " << e; }
catch (...)      { cout << "any other"; }
  • Multiple catch blocks can follow one try block.
  • catch(...) catches any type.
  • Standard exceptions are in <exception>, such as bad_alloc (memory failure) and out_of_range.
  • Using throw; alone inside a catch throws the same exception again.

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 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

KeywordRole in Program
throwThrows a string message when denominator is 0
tryWraps the call to divide() that may fail
catchCatches the thrown string and displays the error
  • When denominator is not zero, the division executes normally.
  • When denominator is zero, throw transfers control directly to the catch block, skipping the remaining try block.
  • After the catch block executes, the program continues normally, demonstrating graceful error handling.
Open this answer on its own page →

2081 · 5 marks

Why do we need to handle exception? Illustrate with an example. [5]

An exception is an abnormal event detected while a program is running, such as a file that will not open, a request for memory that cannot be met, or an argument that makes an operation meaningless. In C++ the code that detects the trouble signals it with throw, and the code that knows what to do...

Open this answer on its own page →

2080 · 5 marks

What is exception handling? Explain types of exception handling and explain with suitable example. [5]

Show solved 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

ConstructPurpose
tryEncloses code whose exceptions are to be handled
catchHandles one type of exception; several may follow one try
throwRaises an exception, or rethrows the current one when written bare
catch (...)Catches an exception of any type at all
noexceptPromises 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 it std::invalid_argument, std::out_of_range, std::domain_error, std::length_error.
  • Runtime errors, faults only detectable while running: std::runtime_error, and under it std::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.

Open this answer on its own page →

2078 · 5 marks

What is exception handling? Explain how to handle an exception with appropriate example. [5]

Show solved 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

ConstructPurpose
tryEncloses the code whose exceptions are to be handled
catchHandles one type of exception; several may follow one try
throwRaises an exception; written bare inside a handler it rethrows the current one
catch (...)Catches an exception of any type whatsoever
DestructorsRun 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.

Open this answer on its own page →

0 · 5 marks

Write a program to handle "array index out of range" exception. [5]

A raw array subscript in C++ is not checked. Writing numbers[10] on an array of five elements does not throw anything and does not report an error; it simply reads or writes memory that does not belong to the array, which is undefined behaviour. There is no equivalent of Java's ArrayIndexOutOfBou...

Open this answer on its own page →

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]

Suppose data.txt contains: Program Output: Concept Description ------ ifstream Used to open and read from a file getline() Reads one complete line at a time inFile check Verifies file was opened successfully line.length() Returns number of characters in a line Word counting Detects transition fro...

Open this answer on its own page →

2079 · 5 marks

Define stream. How do you read the text from file? Describe. [5]

A stream is an abstraction for a flow of characters between a program and some source or destination of data, such as a file, the keyboard, the screen, or a block of memory. The program deals only with the stream, and the library deals with the device behind it, so the same insertion and extracti...

Open this answer on its own page →

2078 · 5 marks

Write a program that writes the contents of file 1 into file 2. [5]

--- Step Function Used Purpose ----------------------------- Open file1 fopen("file1.txt", "r") Opens file1 in read mode Open file2 fopen("file2.txt", "w") Opens file2 in write mode (creates if not exists) Read character fgetc(file1) Reads one character at a time from file1 Write character fputc(...

Open this answer on its own page →

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]

  1. Read text input from the keyboard 2. Write the text to a file named "test.txt" 3. Read back the content from "test.txt" 4. Display the content on the monitor --- --- --- Function Purpose ------------------- fopen("test.txt", "w") Opens file for writing (creates if not exists) fopen("test.txt",...
Open this answer on its own page →

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 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

StepDescription
cin >> numReads 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 << numWrites 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 use ios::out if overwriting is acceptable.

Open this answer on its own page →

2080.1 · 5 marks

Write a program that writes objects to a binary file and reads objects from the same file. [5]

Binary file I/O in C++ allows storing objects (structured data) directly in binary format using fstream. The key functions used are: - write() - writes raw bytes of an object to a binary file - read() - reads raw bytes from a binary file back into an object --- --- --- Feature Description ------ ...

Open this answer on its own page →

Stream manipulators

2081 · 5 marks

Illustrate the use of set w and set precision with example. [5]

setw and setprecision are output formatting manipulators defined in the header file <iomanip. They are used to control the appearance of output in C++. --- - Sets the minimum field width for the next output value. - The output is right-aligned by default within the specified width. - It applies o...

Open this answer on its own page →

File handling with objects

2080 · 5 marks

Write a Program to read and write values through object using File Handling. [5]

File handling in C++ allows storing and retrieving object data (attributes) to/from files using fstream. We use write() to store binary data and read() to retrieve it. --- --- --- Feature Description ------ fstream Used for both reading and writing ios::out \ ios::binary Opens file in binary writ...

Open this answer on its own page →

Namespace definition

2079 · 5 marks

Define namespace. List any two manipulators with their uses. [5]

A namespace is a declarative region that provides a scope to the identifiers (names of types, functions, variables, etc.) inside it. It is used to organize code into logical groups and to prevent name collisions that can occur especially when a codebase includes multiple libraries. Members of a n...

Open this answer on its own page →

Try, catch, and throw statements

2080.1 · 5 marks

Illustrate Exception handling in C++ using try, throw and catch statements. [5]

Exception handling is a mechanism in C++ that allows a program to detect and handle runtime errors (exceptions) gracefully, without crashing the program. C++ provides three keywords for exception handling: Keyword Purpose ------------------ try Encloses the block of code that might throw an excep...

Open this answer on its own page →