2078 11

BIT153 ยท 2078 ยท 5 marks

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

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

Object Oriented ProgrammingChapter 10: Exception Handling and File I/OException handling definition and purpose

Quick answer

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.

Exception Handling in C++ and How an Exception Is Handled

What exception handling is

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.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.