Java Handle Related Failures Without Hiding Differences
A multi-catch can share one recovery path for several exception types. Separate handlers remain useful when failures require different responses.
Understand the idea
Catch more specific exception types before broader ones so a general handler does not make a later specific handler unreachable. In a multi-catch, the listed alternatives cannot have a subtype relationship that makes one redundant. A finally block runs during normal completion and many exceptional exits, but it is not a guarantee against process termination or machine failure.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
public class Main {
public static void main(String[] args) {
try {
int seats = Integer.parseInt("4");
if (seats > 3) throw new IllegalArgumentException("capacity exceeded");
} catch (IllegalArgumentException failure) {
System.out.println("Invalid booking: " + failure.getMessage());
} finally {
System.out.println("Request finished");
}
}
}
Expected output
Invalid booking: capacity exceeded
Request finishedNumberFormatException is an IllegalArgumentException subtype, so this single handler covers both parse rejection and the explicit range rejection. That is a deliberate small example; a user interface might want different messages for those failures. Finally records completion without attempting to claim that the booking succeeded.
Check the official Java documentation for detailed contracts and supported options.