What this topic covers
15 subtopics- Control flow9
- Exception hierarchy7
- Design5
- Exception types5
- Chaining4
- Custom exceptions2
- Exception safety2
- Resources2
- Rethrowing2
- Stack unwinding2
- Assertions1
- Destructors1
Show all 15 subtopics
- Exception groups1
- noexcept1
- Uncaught exceptions1
- Beginner 15
- Intermediate 15
- Advanced 15
About this topic
Exceptions separate the normal path from error handling. Objects matter here: exceptions are objects in a class hierarchy, so the most specific catch must come first, and you design your own exception classes for your domain. Output questions test the exact order of try, catch, finally (and Python's else), what happens when finally returns, and which destructors run while the stack unwinds. Every program here was run.
Free preview
Sample questions
Try each one first, then open the answer for the explanation and why the other options are wrong.
What does this print?
public class Main {
public static void main(String[] args) {
try {
System.out.print("try ");
int x = 10 / 0;
System.out.print("unreached ");
} catch (ArithmeticException e) {
System.out.print("catch ");
} finally {
System.out.print("finally ");
}
System.out.println("after");
}
}
Show answer and explanation
Explanation
The exception jumps straight to the matching catch, skipping the rest of the try block. finally always runs, then execution continues after the statement.
Why the other options are wrong
- Afinally always runs.
- Ccatch runs before finally.
- DCode after the throw point is skipped.
Both try and finally return. What does this print?
public class Main {
static int value() {
try {
return 1;
} finally {
return 2;
}
}
static int counter() {
int x = 10;
try {
return x;
} finally {
x = 99;
}
}
public static void main(String[] args) {
System.out.println(value() + " " + counter());
}
}
Show answer and explanation
Explanation
A return in finally replaces the pending return (and would even swallow an exception) – never do it. In counter(), the value 10 is captured when return x runs; changing x in finally does not change it.
Why the other options are wrong
- Afinally's return wins.
- BThe returned value was already 10.
- CBoth parts are wrong.
Does finally run if the JVM exits inside try? What does this print?
public class Main {
public static void main(String[] args) {
try {
System.out.print("try ");
System.exit(0);
} finally {
System.out.print("finally ");
}
System.out.print("after");
}
}
Show answer and explanation
Explanation
System.exit stops the JVM (after running shutdown hooks), so control never returns to execute finally. finally is guaranteed for normal and exceptional completion, not for the process ending (or a killed thread, power loss…).
Why the other options are wrong
- Btry prints first.
- CNothing after exit runs.
- Dexit does not return.