Loading lessons...
Exception Handling
Exception Handling
Programs meet unusual situations at run time: division by zero, a missing file, an array index out of range, memory running out. Returning error codes clutters every call with checks and is easy to ignore. C++ exception handling separates the error-handling code from the normal code: the place that detects a problem throws an exception, and a place that knows how to handle it catches it.
1. Errors and Exceptions
| Kind of error | When | Example |
|---|---|---|
| Syntax / compile-time errors | found by the compiler | a missing ; |
| Logic errors | the program runs but gives wrong results | using < instead of <= |
| Exceptions (run-time anomalies) | unusual conditions during execution | division by zero, file not found, out of memory |
Exceptions are of two kinds:
- Synchronous exceptions are caused by the program's own operations, such as an out-of-range index or overflow. C++ exception handling deals with these.
- Asynchronous exceptions are caused by events outside the program's control, such as keyboard interrupts or hardware failures. C++ exception handling does not handle them.
2. The Exception Handling Mechanism
C++ uses three keywords:
| Keyword | Role |
|---|---|
try | marks a block of code that may cause an exception |
throw | raises (throws) an exception when a problem is detected |
catch | handles an exception of a given type; follows a try block |
The process has four steps: find the problem (hit the exception), inform that an error occurred (throw), receive the error information (catch), and take corrective action (handle).
try, throw and catch: control jumps from the throw to the matching catch
#include <iostream>
using namespace std;
int main() {
int a = 20, b = 15, c = 15;
try {
if ((b - c) != 0) {
cout << "Result (a/x) = " << a / (b - c) << endl;
} else {
throw(b - c); // throw an int
}
cout << "This line is skipped when an exception is thrown" << endl;
} catch (int x) { // catches the int thrown above
cout << "Exception caught: divide by zero, x = " << x << endl;
}
cout << "End of program" << endl;
return 0;
}Output:
Exception caught: divide by zero, x = 0
End of programWhen throw runs, control leaves the try block immediately and jumps to the first catch whose parameter type matches. After the handler, execution continues after the last catch block. If no exception is thrown, all the catch blocks are skipped.
3. Throwing from a Function
Exceptions are usually thrown inside a function called from the try block. The exception travels back up the chain of calls until a matching handler is found.
#include <iostream>
using namespace std;
double divide(double x, double y) {
if (y == 0) {
throw "Division by zero!"; // throw a C string
}
return x / y;
}
int main() {
double pairs[3][2] = {{10, 4}, {7, 0}, {9, 3}};
for (int i = 0; i < 3; i++) {
try {
cout << pairs[i][0] << " / " << pairs[i][1] << " = ";
cout << divide(pairs[i][0], pairs[i][1]) << endl;
} catch (const char* msg) {
cout << "error: " << msg << endl;
}
}
return 0;
}Output:
10 / 4 = 2.5
7 / 0 = error: Division by zero!
9 / 3 = 3Stack unwinding
As an exception travels up through functions, each function it leaves is exited, and destructors run for every local object that was fully constructed. This is called stack unwinding, and it is why RAII (Lesson 18) prevents leaks even when exceptions occur.
#include <iostream>
using namespace std;
class Guard {
const char* name;
public:
Guard(const char* n) : name(n) {
cout << " acquire " << name << endl;
}
~Guard() {
cout << " release " << name << endl;
}
};
void level2() {
Guard g("resource in level2");
throw 42; // leaves level2 and level1
}
void level1() {
Guard g("resource in level1");
level2();
cout << " never printed" << endl;
}
int main() {
try {
level1();
} catch (int e) {
cout << "caught " << e << " in main" << endl;
}
return 0;
}Output:
acquire resource in level1
acquire resource in level2
release resource in level2
release resource in level1
caught 42 in main4. Multiple Catch Blocks and Catch-All
A try block can be followed by several catch blocks, one per exception type. They are tested in order, and the first match is used. A handler catch(...) (three dots) catches any exception; it must be last.
#include <iostream>
using namespace std;
void test(int x) {
try {
if (x == 1) {
throw x; // int
} else if (x == 0) {
throw 'x'; // char
} else if (x == -1) {
throw 1.0; // double
} else if (x == 2) {
throw "text"; // const char*
}
cout << " no exception for " << x << endl;
} catch (char c) {
cout << " caught a char: " << c << endl;
} catch (int m) {
cout << " caught an int: " << m << endl;
} catch (double d) {
cout << " caught a double: " << d << endl;
} catch (...) {
cout << " caught something else (catch-all)" << endl;
}
}
int main() {
int values[5] = {1, 0, -1, 2, 5};
for (int i = 0; i < 5; i++) {
cout << "x = " << values[i] << endl;
test(values[i]);
}
return 0;
}Output:
x = 1
caught an int: 1
x = 0
caught a char: x
x = -1
caught a double: 1
x = 2
caught something else (catch-all)
x = 5
no exception for 5Matching rules
- The type must match exactly; no ordinary conversions are applied (an
intis not caught bycatch(double)). - The exceptions are: a derived-class object is caught by a handler for its base class, and pointer/array conversions such as
char[]toconst char*. - So handlers for derived classes must come before handlers for their bases, and
catch(...)must be last.
5. Rethrowing an Exception
A handler may decide it cannot fully deal with an exception and pass it on to an outer handler by writing throw; with no operand. The same exception object is rethrown.
#include <iostream>
using namespace std;
void process(int x) {
try {
if (x < 0) {
throw x;
}
cout << "processed " << x << endl;
} catch (int e) {
cout << "process(): logging error " << e << ", rethrowing" << endl;
throw; // pass the same exception on
}
}
int main() {
try {
process(5);
process(-3);
} catch (int e) {
cout << "main(): handled error " << e << endl;
}
return 0;
}Output:
processed 5
process(): logging error -3, rethrowing
main(): handled error -36. Throwing Objects of Classes
Throwing objects carries more information than an int, and a class hierarchy of exceptions lets one handler catch a whole group. Exceptions are best thrown by value and caught by reference.
#include <iostream>
using namespace std;
class BankError { // base exception class
public:
virtual const char* what() const {
return "bank error";
}
virtual ~BankError() {}
};
class InsufficientFunds : public BankError {
double needed;
public:
InsufficientFunds(double n) : needed(n) {}
const char* what() const {
return "insufficient funds";
}
double shortBy() const {
return needed;
}
};
class InvalidAmount : public BankError {
public:
const char* what() const {
return "invalid amount";
}
};
class Account {
double balance;
public:
Account(double b) : balance(b) {}
void withdraw(double amt) {
if (amt <= 0) {
throw InvalidAmount();
}
if (amt > balance) {
throw InsufficientFunds(amt - balance);
}
balance = balance - amt;
cout << "withdrew " << amt << ", balance " << balance << endl;
}
};
int main() {
Account acc(1000);
double requests[3] = {300, -50, 900};
for (int i = 0; i < 3; i++) {
try {
acc.withdraw(requests[i]);
} catch (InsufficientFunds& e) { // derived first
cout << "Error: " << e.what() << " (short by " << e.shortBy() << ")" << endl;
} catch (BankError& e) { // then the base: catches InvalidAmount
cout << "Error: " << e.what() << endl;
}
}
return 0;
}Output:
withdrew 300, balance 700
Error: invalid amount
Error: insufficient funds (short by 200)7. Exception Specifications (C++98)
C++98 allows a function to list the exceptions it may throw, with a throw list after the parameter list:
| Specification | Meaning |
|---|---|
void f() throw(int, double) | f may throw only int or double |
void f() throw() | f throws no exceptions |
void f() (no specification) | f may throw anything |
If a function throws a type not in its list, unexpected() is called, which by default terminates the program. Dynamic exception specifications were deprecated in C++11 and removed in C++17; modern code uses noexcept instead of throw().
8. Standard Exceptions
The standard library throws objects of classes derived from std::exception (header <exception> and <stdexcept>). Each has a what() member function returning a message.
| Class | Thrown when |
|---|---|
bad_alloc | new cannot allocate memory |
bad_cast | dynamic_cast to a reference fails |
bad_typeid | typeid is applied to a null pointer of polymorphic type |
out_of_range | an index is invalid, e.g. vector::at() or string::at() |
invalid_argument | an argument has an invalid value |
length_error | an object would exceed its maximum size |
overflow_error, underflow_error, range_error | arithmetic and range problems (thrown by user code or some library functions) |
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
int main() {
vector<int> v(3, 7);
try {
cout << "v.at(1) = " << v.at(1) << endl;
cout << "v.at(5) = " << v.at(5) << endl; // throws out_of_range
} catch (out_of_range&) {
cout << "out_of_range caught: index 5 is invalid" << endl;
}
try {
throw invalid_argument("age cannot be negative");
} catch (exception& e) { // the base class catches all standard exceptions
cout << "exception: " << e.what() << endl;
}
return 0;
}Output:
v.at(1) = 7
out_of_range caught: index 5 is invalid
exception: age cannot be negative9. Uncaught Exceptions
If an exception is thrown and no handler matches anywhere up the call chain, the function terminate() is called, which by default calls abort() and ends the program abnormally. set_terminate() can install a different final handler, but the program still ends.
Key points to remember
tryencloses risky code,throwraises an exception,catch(type)handles it; control never returns to the throw point.- Exceptions travel up the call stack; destructors of local objects run on the way (stack unwinding).
- Multiple catch blocks are tried in order;
catch(...)catches everything and must be last; derived-class handlers go before base-class handlers. throw;rethrows the current exception; an unhandled exception callsterminate().- Throw objects (by value) and catch by reference; standard exceptions derive from
std::exceptionand havewhat().
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. What is exception handling? Explain the
try,throwandcatchmechanism with a program. (10 Marks) - Write: the types of errors, synchronous vs asynchronous, the three keywords and four steps, the diagram, and the divide-by-zero program.
- Q2. Write a program with multiple catch blocks and a catch-all handler. (5 Marks)
- Write: the
test(x)program and the matching rules. - Q3. What is rethrowing an exception? Explain with an example. (5 Marks)
- Q4. How can user-defined classes be used as exceptions? Write a program. (5 Marks)
- Write: the
BankErrorhierarchy and why derived handlers come first. - Q5. What is stack unwinding? What are exception specifications? (5 Marks)