Try catch finally and throwing
What you will learn
A try block groups work that may fail. A catch block handles a matching exception; finally normally executes as control leaves the try or catch.
- Trace normal and exceptional control flow through try/catch/finally.
- Translate a failure while preserving its original cause.
Each example is a standalone Main.java. Compile with javac --release 21 Main.java and run with java Main. Java 25 execution remains unverified.
public class Main { public static void main(String[] args) { try { System.out.println("Start"); Integer.parseInt("three"); System.out.println("Parsed"); } catch (NumberFormatException e) { System.out.println("Use digits"); } finally { System.out.println("Attempt finished"); } System.out.println("Next"); }}Expected output:
StartUse digitsAttempt finishedNextThe failing call skips the remaining try statements. The matching catch executes before finally.
Choose specific handlers and preserve failure context
Java selects the first applicable catch by the runtime exception type. Arrange subtype handlers before broader handlers; reversing them can make a later catch unreachable. Multi-catch uses | between alternatives that cannot be related by subclassing. Its exception parameter cannot be reassigned. Finally executes on normal completion, return or exception propagation, provided execution reaches that exit normally or abruptly; it is not guaranteed after JVM termination or a nonterminating block. If finally throws or returns, it may replace a pending exception or return value. Avoid control transfers from finally. Use exception messages to communicate actionable context, and retain the original cause using a constructor that accepts a Throwable. The cause describes why the new exception occurred, not a cleanup failure.
public class Main { public static void main(String[] args) { String[] inputs = {"abc", "0", "4"}; for (String input : inputs) { try { System.out.println(20 / Integer.parseInt(input)); } catch (NumberFormatException | ArithmeticException e) { System.out.println("Invalid divisor"); } } }}Expected output:
Invalid divisorInvalid divisor5Multi-catch shares a response for two unrelated exception types.
A practical variation
class QuantityException extends Exception { private static final long serialVersionUID = 1L; QuantityException(String message, Throwable cause) { super(message, cause); }}public class Main { static int parse(String text) throws QuantityException { try { return Integer.parseInt(text); } catch (NumberFormatException e) { throw new QuantityException("Quantity must be an integer", e); } } public static void main(String[] args) { try { parse("two"); } catch (QuantityException e) { System.out.println(e.getMessage()); System.out.println(e.getCause().getClass().getSimpleName()); } }}Expected output:
Quantity must be an integerNumberFormatExceptionThe new exception explains the domain failure and retains the original reason. serialVersionUID avoids a serialization lint warning; no serialization is used.
Common mistakes
Avoid empty catches and return statements in finally. They can hide important failures. Do not expose arbitrary internal stack traces to end users.
Practice
Implement parseSeats(String text) accepting integers 1–40. Wrap NumberFormatException in IllegalArgumentException with message Seats must be an integer and the cause; reject out-of-range numbers separately. Check 1, 40, 0 and abc.
Hints:
- Catch only the parsing operation; check the range after parsing.
- Use new IllegalArgumentException(message, e) for the parsing failure.
Related reference topics: Java try/catch/finally, Java Multi-catch, Java throw statement, Java Throwable.getCause(). Next: Try-with-resources.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Try catch finally and throwing — knowledge check
Apply Java exception and inventory contracts using Java 21-compatible examples.
Which handler must come first for these two types?
Which syntax shares a handler?
What if finally throws while another exception is pending?
How do you retain a parsing failure when wrapping it?
What follows a throwing statement in the same try path?