Exception handling separates error handling from normal logic: code that detects a problem throws, and a matching handler catches it. Covers C++ try/throw/catch, stack unwinding and std::exception, and Java's checked/unchecked hierarchy, finally, throws, custom exceptions and try-with-resources.
High-yield 70 minSyllabus: “Exception handling”
Mark as
The idea in one minute
A clerk processing an allotment file finds a missing signature. She does not fix it at her desk or quietly ignore it; she raises a query slip (throw) that travels up the chain of officers until one who is authorised to deal with it handles it (catch). Every officer the slip passes on the way closes the files they had open (stack unwinding), and whatever happens, the office is locked at 5 pm (finally).
Key points — the night-before list
An exception is an abnormal run-time condition (divide by zero, bad index, missing file). C++ exception handling covers synchronous exceptions only — not hardware or keyboard interrupts.
C++: throw any type; catch matches by type with only derived-to-base (and pointer/const) conversions; catch(...) catches everything and goes last; throw; rethrows.
Stack unwinding: as an exception leaves each function, destructors of its local objects run — the basis of RAII. No matching handler anywhere → std::terminate().
Java: Throwable → Error (unchecked) and Exception; Exception → RuntimeException (unchecked) and the checked ones: IOException, SQLException, ClassNotFoundException, InterruptedException.
Checked = the compiler enforces 'catch or declare'. throw raises one exception object; throws in a method signature declares what may escape.
finally always runs — even after return; only System.exit() or a dying JVM skips it. A return inside finally overrides the try's return value.
Catch subclasses before superclasses (in Java the reverse is a compile error). Java 7 added multi-catch catch (A | B e) and try-with-resources (AutoCloseable, closed in reverse order).
01Errors, exceptions and why exception handling exists
Programs go wrong in three ways. Compile-time errors (syntax, type mismatches) stop the build. Logic errors produce wrong answers without any complaint. Run-time errors — dividing an integer by zero, indexing past the end of an array, opening a file that does not exist, running out of memory — happen during execution. These abnormal run-time conditions are called exceptions.
The traditional C approach returns an error code (−1, NULL, errno). Every caller must remember to check it, the checks clutter the normal logic, an unchecked code silently lets the program continue in a broken state, and a constructor has no return value to carry a code at all.
C++Two ways to report the same failure
#include <string>
using namespace std;
// Error-code style: every caller must remember to check the result
int parseAge(const string& s, int& out); // returns 0 on success, -1 on error// Exception style: the failure cannot be ignored by accident
int parseAge(const string& s); // returns the age or throws invalid_argument
The exception-handling mechanism (Balagurusamy's four steps)
Find the problem (hit)
Code detects that it cannot continue — a zero divisor, a negative age, a missing file.
Inform that an error occurred (throw)
It creates an exception object describing the problem and throws it; normal execution stops there.
Receive the error information (catch)
The runtime searches outward through the calling functions for a handler whose type matches.
Take corrective action (handle)
The handler logs, retries, uses a default or reports to the user; execution continues after it.
Synchronous exceptions arise from the program's own operations — out-of-range index, overflow, failed allocation. These are what C++ and Java exception handling deal with.
Asynchronous events come from outside the program's flow — keyboard interrupts, hardware faults. C++ try/catch does not handle them (signals do).
02C++: try, throw and catch
Code that might fail is placed in a try block. When a problem is detected, a throw expression creates an exception object and transfers control out of the try block immediately. The catch handlers that follow the try block are examined in order; the first whose parameter type matches runs, and execution then continues after the last handler. If none matches, the exception propagates to the calling function; if it is never caught, std::terminate() ends the program.
try {
statements; // may throw directly or in functions they call
throw expression; // creates and throws an exception object
}
catch (Type1 e) { handler for Type1 }
catch (const Type2& e) { handler for Type2 }
catch (...) { handler for anything else — must be last }
General form
C++Handlers are tried in order (prints: k=0 fine / int 10 / logic_error: index 9 / exception: disk full / unknown)
#include <iostream>#include <stdexcept>
using namespace std;
void risky(int k) {
if (k == 1) throw 10; // an int
if (k == 2) throw out_of_range("index 9"); // derived from logic_error
if (k == 3) throw runtime_error("disk full");
if (k == 4) throw 'x'; // a char
cout << "k=" << k << " fine\n";
}
int main() {
for (int k = 0; k <= 4; k++) {
try {
risky(k);
} catch (int n) {
cout << "int " << n << "\n";
} catch (const logic_error& e) { // catches out_of_range (derived -> base)
cout << "logic_error: " << e.what() << "\n";
} catch (const exception& e) { // the most general standard type
cout << "exception: " << e.what() << "\n";
} catch (...) { // anything else, e.g. the char
cout << "unknown\n";
}
}
}
A handler matches if its type is the same as the thrown type, or a public base class of it (so list derived handlers before base ones), or by pointer conversion to a base pointer or void*, plus adding const.
No arithmetic conversions: throw 5; is not caught by catch (double) or catch (long), and throw 'x'; is not caught by catch (int).
catch (...) matches anything and must be the last handler.
Catch class types by reference — catch (const exception& e) — to avoid copying and slicing, so the virtual what() returns the derived message.
C++Rethrowing, and the no-conversion rule (prints: inner logs: sensor offline / main handles: sensor offline / 5 is an int, so only catch(...) matched)
#include <iostream>#include <stdexcept>
using namespace std;
void inner() {
try {
throw runtime_error("sensor offline");
} catch (const exception& e) {
cout << "inner logs: " << e.what() << "\n";
throw; // rethrow the SAME object upward
}
}
int main() {
try {
inner();
} catch (const runtime_error& e) {
cout << "main handles: " << e.what() << "\n";
}
try {
throw 5;
} catch (double d) { // no int -> double conversion here
cout << "double\n";
} catch (...) {
cout << "5 is an int, so only catch(...) matched\n";
}
}
Inside a handler, a bare throw; rethrows the original exception object unchanged, letting a lower level log the problem and a higher level handle it. Writing throw e; instead throws a copy of the static type of e — with catch (const exception& e) that would slice a runtime_error down to a plain exception.
03Stack unwinding and RAII
When an exception is thrown, control leaves the current function and every function in between until a matching handler is found. For each function exited this way, the destructors of its fully constructed local objects run, in reverse order of construction. This orderly dismantling of stack frames is stack unwinding.
C++Destructors run while the exception travels to main
In the second call, parse throws: its Guard is destroyed (release parser), then process is abandoned before printing — its Guard is destroyed too (release file) — and only then does main's handler run. Because the destructors ran, nothing leaked even though two functions were cut short. The step-through sequence on this page animates exactly this run.
Tie every resource to an object whose destructor releases it — RAII (std::fstream, std::lock_guard, smart pointers).
Never let an exception escape a destructor: throwing during unwinding calls std::terminate(), and since C++11 destructors are implicitly noexcept.
If a constructor throws, the object never existed, so its destructor does not run — but its already-constructed members and base parts are destroyed.
Note
C++ has no finally keyword. RAII destructors do that job — and they also run on normal exit, so clean-up code is written once instead of twice.
04Standard exception classes and noexcept
Class
Derives from
Typical source
exception
— (root, header <exception>)
Base of all standard exceptions; virtual const char* what()
logic_error
exception
A mistake in program logic that could be found before running
invalid_argument
logic_error
std::stoi("abc")
out_of_range
logic_error
vector::at(99) on a 3-element vector
length_error
logic_error
Growing a string beyond max_size()
domain_error
logic_error
Mathematical domain errors (used by libraries and user code)
runtime_error
exception
Errors detectable only while running
overflow_error, underflow_error, range_error
runtime_error
Arithmetic results out of range
bad_alloc
exception (header <new>)
new cannot obtain memory
bad_cast, bad_typeid
exception (header <typeinfo>)
Failed dynamic_cast to a reference; typeid of a null polymorphic pointer
The std::exception family
C++A user-defined exception that fits the standard hierarchy (prints: balance too low, short by 200)
#include <iostream>#include <stdexcept>
using namespace std;
class InsufficientFunds : public runtime_error {
public:
double shortBy;
InsufficientFunds(const string& msg, double s) : runtime_error(msg), shortBy(s) {}
};
class Account {
double balance = 1000;
public:
void withdraw(double amt) {
if (amt > balance) throw InsufficientFunds("balance too low", amt - balance);
balance -= amt;
}
};
int main() {
Account a;
try {
a.withdraw(300);
a.withdraw(900); // only 700 left
} catch (const InsufficientFunds& e) {
cout << e.what() << ", short by " << e.shortBy << "\n";
} catch (const exception& e) {
cout << "other: " << e.what() << "\n";
}
}
noexcept (C++11) declares that a function will not throw. If it throws anyway, std::terminate() is called immediately — no handler gets a chance. The promise also enables optimisations: std::vector moves its elements during reallocation only if their move constructor is noexcept. The old dynamic exception specifications such as void f() throw(int) were deprecated in C++11 and removed in C++17 (throw() in C++20).
05Java's exception hierarchy: checked and unchecked
In Java only objects of class Throwable or its subclasses can be thrown. Throwable has two branches. Error represents serious problems an application should not try to recover from — OutOfMemoryError, StackOverflowError. Exception represents conditions a program might reasonably handle; inside it, the RuntimeException subtree covers programming mistakes such as null references and bad indexes.
The key part of the hierarchy (all in java.lang unless noted)
Checked exceptions are subclasses of Exception outside the RuntimeException branch. For them the compiler enforces the catch-or-specify rule: a method that can throw one must either catch it or declare it with throws. Unchecked exceptions — RuntimeException, Error and their subclasses — need neither.
Exception
Checked?
Typical cause
ArithmeticException
Unchecked
Integer division by zero: int x = 5 / 0;
NullPointerException
Unchecked
Using null as an object: String s = null; s.length();
ArrayIndexOutOfBoundsException
Unchecked
int[] a = new int[3]; a[3] = 1;
StringIndexOutOfBoundsException
Unchecked
"abc".charAt(5)
ClassCastException
Unchecked
Object o = "hi"; Integer i = (Integer) o;
NumberFormatException
Unchecked (extends IllegalArgumentException)
Integer.parseInt("12a")
ArrayStoreException
Unchecked
Storing a String into an Object[] that is really an Integer[]
IOException
Checked
Any failed input/output operation
FileNotFoundException
Checked (extends IOException)
new FileReader("missing.txt")
ClassNotFoundException
Checked
Class.forName("NoSuchClass")
InterruptedException
Checked
A thread in sleep(), wait() or join() is interrupted
StackOverflowError, OutOfMemoryError
Errors (unchecked)
Runaway recursion; heap exhausted
Exceptions that appear in almost every paper
Watch out
Floating-point division never throws: 5.0 / 0 gives Infinity and 0.0 / 0 gives NaN. Only integer / and % by zero throw ArithmeticException (message: '/ by zero').
06try, catch, finally — the order of execution
A Java try block must be followed by at least one catch, or a finally, or both (try-with-resources may have neither). The finally block holds clean-up code that must run however the try block ends.
Execution rules
Run the try block
Statements execute normally until the block ends or an exception is thrown.
On an exception, skip the rest of try
The catch clauses are examined top to bottom; the first whose type matches the exception (same class or a superclass) runs. Later catches are ignored.
Run finally — always
After a normal try, after a catch that handled the exception, or just before an unhandled exception leaves the method.
Continue or propagate
If the exception was handled (or none occurred), execution continues after the whole statement; otherwise the exception propagates to the caller.
JavaWhich lines print? (A, D, E, F)
public class Flow {
public static void main(String[] args) {
try {
System.out.println("A");
int[] a = new int[2];
a[2] = 5; // index 2 does not exist
System.out.println("B"); // skipped
} catch (ArithmeticException e) {
System.out.println("C"); // type does not match
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("D"); // this handler runs
} finally {
System.out.println("E"); // always
}
System.out.println("F"); // handled, so execution continues
}
}
Javafinally and return — the classic output question
public class Finally {
static int f1() {
try { return 1; }
finally { System.out.println("finally f1"); } // runs before the method returns
}
static int f2() {
try { return 1; }
finally { return 2; } // overrides the try's return value
}
static int f3() {
int x = 10;
try { return x; } // the value 10 is saved here
finally { x = 20; } // changing x afterwards has no effect
}
public static void main(String[] args) {
System.out.println(f1());
System.out.println(f2());
System.out.println(f3());
}
}
/* Output:
finally f1
1
2
10 */
System.exit() is called in the try or catch block.
The JVM crashes or is killed, or the machine loses power.
The try block never finishes — an infinite loop or a deadlock.
It runs in a daemon thread and the JVM exits because all user threads have ended.
Watch out
Never return from a finally block: it overrides the try's return value and silently discards any exception that was propagating.
Catch order matters: a superclass handler before a subclass handler makes the subclass handler unreachable, and Java rejects it ('exception FileNotFoundException has already been caught'); C++ merely warns. Java 7's multi-catch handles unrelated types in one block — catch (IOException | SQLException e) — but the alternatives may not be subclasses of each other, and e is implicitly final.
07throw, throws, custom exceptions and try-with-resources
throw
A statement inside a method body
Followed by one Throwable object: throw new X("msg");
Actually raises the exception
Control leaves immediately
throws
A clause in the method signature
Followed by one or more exception class names
Declares what may escape the method
Mandatory for checked exceptions that are not caught inside
JavaA custom checked exception, throw, throws and finally together
class InsufficientFundsException extends Exception { // checked: extends Exception
private final double shortBy;
InsufficientFundsException(String msg, double shortBy) {
super(msg); // message for getMessage()
this.shortBy = shortBy;
}
double getShortBy() { return shortBy; }
}
class Account {
private double balance = 1000;
void withdraw(double amt) throws InsufficientFundsException { // must be declared
if (amt > balance)
throw new InsufficientFundsException("Balance too low", amt - balance);
balance -= amt;
}
}
public class BankApp {
public static void main(String[] args) {
Account a = new Account();
try {
a.withdraw(300);
a.withdraw(900); // only 700 left
System.out.println("not printed");
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage() + ", short by " + e.getShortBy());
} finally {
System.out.println("transaction closed");
}
}
}
/* Output:
Balance too low, short by 200.0
transaction closed */
Extend Exception for a checked custom exception (callers are forced to deal with it) or RuntimeException for an unchecked one. Useful Throwable methods: getMessage(), toString() (class name plus message), printStackTrace(), getCause() for chained exceptions — throw new ServiceException("save failed", e); — and getSuppressed().
try-with-resources (Java 7) declares resources in parentheses after try. Each must implement AutoCloseable (or its subinterface Closeable); they are closed automatically, in reverse order of declaration, as soon as the try block ends — before any catch or finally runs. If both the body and close() throw, the close() exception is attached to the main one as a suppressed exception instead of replacing it.
JavaReading the first line safely
import java.io.*;
public class FirstLine {
public static void main(String[] args) {
try (BufferedReader in = new BufferedReader(new FileReader("notes.txt"))) {
System.out.println(in.readLine());
} catch (FileNotFoundException e) { // the subclass first ...
System.out.println("No such file: " + e.getMessage());
} catch (IOException e) { // ... then its superclass
System.out.println("Read failed: " + e);
} // 'in' is closed automatically
}
}
Point
C++
Java
What can be thrown
Any type: int, string, class objects
Only Throwable objects
Catch everything
catch (...)
catch (Throwable t)
Guaranteed clean-up
Destructors (RAII); no finally
finally; try-with-resources
Checked exceptions
None
Yes — catch or declare with throws
Declaring behaviour
noexcept (old throw(...) lists removed)
throws clause
Rethrow inside a handler
throw;
throw e;
Nobody catches it
std::terminate() aborts the program
The thread ends and its stack trace is printed
Standard root class
std::exception
java.lang.Throwable
Exception handling: C++ vs Java
Step through · Stack unwinding: process("") throws from inside parse()
step 1 / 9
Step 1: process("") inside try
main calls process from within its try block, so main's handlers are active for anything thrown below.
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Which lines print?
Trace the Flow program of Section 6: the try block prints A, then executes a[2] = 5; on an array of length 2, then would print B; handlers for ArithmeticException (prints C) and ArrayIndexOutOfBoundsException (prints D); finally prints E; then the program prints F.
EX 2finally versus return
Predict the output of the Finally program in Section 6 (f1 returns 1 and prints in finally; f2 returns 1 but finally returns 2; f3 returns x = 10 and finally sets x = 20).
EX 3Tracing stack unwinding in C++
In the Guard program of Section 3, process("42") succeeds and process("") fails inside parse. Write the full output and explain where each 'release' line comes from.
EX 4Matching C++ handlers in order
For the risky(k) loop of Section 2 (k = 0…4 throws nothing, int 10, out_of_range, runtime_error, char 'x'), which handler runs each time? The handlers are catch(int), catch(const logic_error&), catch(const exception&), catch(...).
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
Predict the output: try { System.out.println("1"); throw new IllegalStateException("x"); } catch (IllegalStateException e) { System.out.println("2"); int y = 10 / 0; System.out.println("3"); } finally { System.out.println("4"); } System.out.println("5"); (inside main).
Q2
Which of these compile in Java? (a) catch (Exception e) {} catch (IOException e) {} (b) catch (IOException e) {} catch (Exception e) {} (c) catch (IOException | Exception e) {} (d) catch (IOException | SQLException e) {}
Q3
Classify as checked exception, unchecked exception or error: FileNotFoundException, NumberFormatException, InterruptedException, ArrayStoreException, ClassNotFoundException, StackOverflowError, CloneNotSupportedException, NullPointerException.
Write a custom checked exception InvalidAgeException and a method static void register(int age) that throws it for ages outside 18–40, plus a main that calls it with 15 inside try/catch and prints the message.
Exam traps
finally runs even after return, break or continue; only System.exit() (or the JVM dying) prevents it. A return in finally overrides the try's value and swallows any pending exception.
Java rejects a superclass catch placed before its subclass ('already been caught'); C++ compiles it with a warning, but the derived handler can never run.
throw (a statement that raises an exception) vs throws (a clause that declares exceptions) — examiners swap them constantly.
Error is not a subclass of Exception: catch (Exception e) does not catch OutOfMemoryError or StackOverflowError — only catch (Throwable t) would.
C++ handler matching performs no arithmetic conversions: throw 5; is not caught by catch (double) or catch (long).
Integer division by zero throws ArithmeticException; floating-point division gives Infinity or NaN with no exception.
Quiz — KPSC style
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Exception handling · Question 1 of 12✓ 0 · ✗ 0
The superclass of all exceptions and errors in Java is
Past-paper questions on this topic
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
Past papers · Question 1 of 6✓ 0 · ✗ 0
Modelled on QP 050/2026 · Deputy Manager (IT) / Assistant Programmer / Computer Programmer etc (20 May 2026), Q.44 (reworded)original paper (PDF)
A C++ program throws an exception for which no matching catch handler exists anywhere. Which function is then invoked?