Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 06 / Topic 2 of 8

try/catch: recovering instead of crashing

Wrap the risky code in a try block. If it throws, Java jumps straight to a matching catch block instead of stopping the program; code after the try/catch keeps running.

try {
    int pinNumber = Integer.parseInt(pin);
    System.out.println("PIN as a number: " + pinNumber);
} catch (NumberFormatException e) {
    System.out.println("Could not read PIN '" + pin + "' as a number: " + e.getMessage());
}
System.out.println("Program kept running after the catch block.");
  • The type in catch (NumberFormatException e) must match the exception thrown (or one of its parent types — more on that below).
  • e is the exception object itself. e.getMessage() gives the same text you saw in the stack trace (For input string: "12ab"), without the trace.
  • Nothing after the line that threw, inside the same try block, runs (the println right after parseInt was skipped) — but everything after the whole try/catch runs normally.

Real output (examples/01_try_catch_basics.java), the same two crashes from section 1, now caught:

$ javac 01_try_catch_basics.java
$ java TryCatchBasics
== Catching NumberFormatException ==
Could not read PIN '12ab' as a number: For input string: "12ab"
Program kept running after the catch block.

== Catching ArrayIndexOutOfBoundsException ==
No 4th amount stored: Index 3 out of bounds for length 3
Program finished normally.

Exit code this time is 0: the program finished normally, because both exceptions were handled.

Full program: examples/01_try_catch_basics.java.

Done here? The practice set for Part 6 — including the solutions — is on the part page.

Search the guide