Stop 07 · Exception Handling & File I/OTopics · 2/8

Try-Catch-Finally

Part of the Java Roadmap

In short

Users type letters where you wanted numbers, and files go missing. try-catch lets your program react calmly instead of crashing with a scary stack trace.

try wraps code that may fail, catch handles specific exceptions, and finally runs whether or not an exception occurred. Multi-catch handles several exception types in one block.

The jaadu leaps between two trapeze bars high in a circus tent while a wide safety net is stretched out below.

Think of it like this

Trapeze with a safety net

At a circus in Kolkata, the trapeze artist tries the jump (try). If she slips, the net catches her (catch). Win or fall, the crew rolls up the equipment at the end of the show (finally). The show goes on either way.

Watch it happen

What happens when book("abc") runs

try
exception
catch
finally
after

1/5Java starts running the try block line by line.

The big ideas

What you need to know

Specific catches first

Java checks catch blocks top to bottom. Put NumberFormatException before Exception, or the compiler complains the second one is unreachable.

Multi-catch

catch (ArrayIndexOutOfBoundsException | NullPointerException e) handles several unrelated types with one block.

finally always runs

Even if the try block returns early, finally still runs. Use it for cleanup like logging or releasing a lock.

Say something useful

Print or log e.getMessage() with context. An empty catch block hides problems and makes bugs very hard to find.

See it in code

Walk through the code

java
1public class SeatBooking {2 3    static int book(String seatInput, int[] seats) {4        try {5            int seatNo = Integer.parseInt(seatInput.trim());6            seats[seatNo - 1] = 1;7            System.out.println("Seat " + seatNo + " booked");8            return seatNo;9        } catch (NumberFormatException e) {10            System.out.println("Not a number: " + seatInput);11        } catch (ArrayIndexOutOfBoundsException | NullPointerException e) {12            System.out.println("Invalid seat: " + e.getMessage());13        } finally {14            System.out.println("Booking attempt logged");15        }16        return -1;17    }18 19    public static void main(String[] args) {20        int[] seats = new int[40];21        book("12", seats);22        book("abc", seats);23        book("99", seats);24    }25}

1/4The happy path. Any line here can throw, and if one does, the lines after it are skipped.

A bus seat booking helper for a 40-seat Volvo. Each call prints "Booking attempt logged", whether the booking worked or not.

Save yourself the pain

Common mistakes

Oops

catch (Exception e) { } // empty, to make the error go away

Do this instead

Catch a specific type and at least log it: System.out.println("Bad input: " + e.getMessage());

Oops

Putting catch (Exception e) above catch (NumberFormatException e).

Do this instead

Order catches from most specific to most general. The compiler rejects a catch that can never be reached.

Oops

Returning a value from finally.

Do this instead

Never return from finally. It silently overrides the try's return value and swallows any exception that was in flight.

Your mission

Bulletproof the calculator

~20 min

Quick check

A try block runs return 5; and there is also a finally block. What happens?

Go deeper

  1. 1Catch NumberFormatException when parsing user input.
  2. 2Order catch blocks from most specific to most general.
  3. 3Never swallow exceptions with an empty catch block; at least log them.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge