BIT153 ยท 2080 ยท 5 marks
What is exception handling? Explain types of exception handling and explain with suitable example.
What is exception handling? Explain types of exception handling and explain with suitable example. [5]
Quick answer
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.
Exception Handling in C++
What exception handling is
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.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.