Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 201 ยท Exceptions

Exceptions and try-catch

Learn Java exceptions - how they propagate, reading stack traces, try-catch-finally, multiple catch blocks, multi-catch, errors vs exceptions and the common built-in exceptions.

Programs meet problems they can't solve on the spot: a user types abc where a number belongs, a file is missing, an index is past the end of an array, a network connection drops. Java reports these situations with exceptions. When something goes wrong, the code that detects the problem creates an exception object describing it and throws it. Normal execution stops, and Java looks for code that has declared it can catch that kind of problem.

This design keeps error handling out of the main logic. You write the normal path straight through, and put the "what if it fails" code in a separate catch block, possibly far away in a method that knows what to do about it. This lesson covers what happens when an exception is thrown, how to read a stack trace, try/catch/finally, multiple and multi-catch blocks, the difference between errors and exceptions, and the built-in exceptions you'll meet most often. Throwing your own comes in the next lesson.

What happens when an exception is thrown

When an exception is thrown, Java abandons the current statement and the rest of the current method. It then walks back up the call stack: to the method that called this one, then to its caller, and so on, looking for a matching catch. This is called propagation. If no method catches it, the exception reaches the top of the thread, Java prints a stack trace, and the thread ends. For the main thread, that means the program exits with status 1.

This example crashes on purpose so you can see a stack trace:

Java An uncaught exception and its stack trace (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The program prints week 1: 6, and then the standard error stream shows:

TEXT
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Main.average(Main.java:7)
	at Main.report(Main.java:11)
	at Main.main(Main.java:16)

Reading a stack trace

Read it from the top:

  1. The first line names the thread (main), the exception class (java.lang.ArithmeticException) and its message (/ by zero). The class tells you what kind of problem; the message gives details.
  2. Each at line is one frame of the call stack: a method and the exact file and line. The top frame is where the exception was thrown (average, line 7). Each line below is the caller of the one above it.
  3. Find the first frame in your own code. In real programs, the top frames often belong to the JDK or a library (at java.base/java.lang.Integer.parseInt(...)). The first line that points into your files is usually where to start looking.

Later in the chapter, you'll see traces with a Caused by: section, which means one exception was wrapped inside another (Custom Exceptions), and Debugging Java Programs covers more techniques.

Catching exceptions with try-catch

To handle an exception, put the code that might throw it in a try block and add a catch block for the exception type:

Java
try {
    // code that might throw
} catch (ExceptionType e) {
    // runs only if an ExceptionType (or a subclass) was thrown in the try block
}

If the try block finishes normally, the catch block is skipped. If an exception of a matching type is thrown, the rest of the try block is skipped, the catch block runs, and the program continues after the whole try/catch statement. The variable e holds the exception object.

Java Skipping bad input instead of crashing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Integer.parseInt throws NumberFormatException for text that isn't a whole number. The loop catches it, counts the bad line and keeps going. Edit the Input box to try your own values.

What an exception object tells you

Every exception is an object whose class extends Throwable, and it carries useful information:

Method Returns
getMessage() The detail message, such as For input string: "abc" (may be null)
toString() The class name plus the message: java.lang.NumberFormatException: For input string: "abc"
getClass().getSimpleName() Just the class name: NumberFormatException
printStackTrace() Prints the full stack trace to standard error
getStackTrace() The frames as an array of StackTraceElement
getCause() The underlying exception, if this one wraps another

For messages to users, a friendly sentence of your own is usually better than getMessage(). For logs, record the whole exception, including its stack trace (Logging).

Multiple catch blocks

A try can have several catch blocks. Java checks them from top to bottom and runs the first one whose type matches. At most one catch block runs.

Java Different catch blocks for different problems

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The input "7" parses fine but is past the end of the array; null makes input.strip() throw NullPointerException. Notice the message for it: since Java 14, NPEs have helpful messages that say exactly which call failed and which value was null. Fields and method results appear by name; a local variable shows as <local6> unless the code was compiled with -g (debug information), which IDEs and build tools normally turn on, and then the message names input. And "0" works, because prices[0] is 100.

Order matters: specific before general

Exception types form a class hierarchy, and a catch block also catches every subclass of its type. So a general type listed first would catch everything, and the specific blocks below it could never run. The compiler rejects that:

Java
try {
    Integer.parseInt(text);
} catch (IllegalArgumentException e) {        // NumberFormatException extends this
    // ...
} catch (NumberFormatException e) {           // error: exception NumberFormatException has already been caught
    // ...
}

Put the most specific types first and the most general last.

Multi-catch

When several exception types need the same handling, list them in one catch with |:

Java
try {
    int index = Integer.parseInt(input);
    IO.println(items[index]);
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
    IO.println("Please enter a valid item number.");
}

Two rules apply. The types in a multi-catch can't be subclasses of each other (catch (IllegalArgumentException | NumberFormatException e) fails with Alternatives in a multi-catch statement cannot be related by subclassing, since the general type already covers the specific one). And the variable e is implicitly final, so you can't assign to it.

finally: code that always runs

A finally block runs after the try (and any catch), no matter how the try ended: normally, with a caught exception, with an uncaught exception, or even with return, break or continue. It's the place for cleanup that must happen in every case.

Java When finally runs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

For "0", the division throws ArithmeticException, which process doesn't catch. The finally block still runs, and then the exception continues up to main. The order of the output shows exactly that.

A few facts about finally:

  • try/finally without catch is legal. It means "I can't handle this problem here, but I must clean up before it propagates."
  • It runs before the method returns, but the return value is computed first. Changing a local variable in finally doesn't change what return x; already returned.
  • It doesn't run if the JVM stops: System.exit(...) inside the try, a killed process or a power failure skip it.
  • Never return or throw from finally. A return in finally replaces the try block's return value and silently discards any exception that was propagating. The compiler warns finally clause cannot complete normally when you compile with -Xlint. Exception Handling Best Practices shows this trap.

For closing files, sockets and database connections, Java has a better tool than finally: try-with-resources, which closes things automatically.

Errors vs exceptions

Everything you can throw or catch extends java.lang.Throwable. It has two main branches:

TEXT
Throwable
โ”œโ”€โ”€ Error                       serious JVM problems: don't catch
โ”‚   โ”œโ”€โ”€ OutOfMemoryError
โ”‚   โ”œโ”€โ”€ StackOverflowError
โ”‚   โ””โ”€โ”€ ...
โ””โ”€โ”€ Exception                   problems a program can reasonably handle
    โ”œโ”€โ”€ IOException             checked: the compiler makes you handle or declare it
    โ”œโ”€โ”€ InterruptedException
    โ”œโ”€โ”€ ...
    โ””โ”€โ”€ RuntimeException        unchecked: usually a bug or bad input
        โ”œโ”€โ”€ NullPointerException
        โ”œโ”€โ”€ IllegalArgumentException
        โ”‚   โ””โ”€โ”€ NumberFormatException
        โ”œโ”€โ”€ IndexOutOfBoundsException
        โ”‚   โ”œโ”€โ”€ ArrayIndexOutOfBoundsException
        โ”‚   โ””โ”€โ”€ StringIndexOutOfBoundsException
        โ”œโ”€โ”€ ArithmeticException
        โ””โ”€โ”€ ...
  • An Error means the JVM itself is in trouble: out of memory, a stack overflow from runaway recursion, a class that can't be loaded. Your program usually can't recover, so don't catch Error or Throwable in ordinary code.
  • An Exception is a condition a well-written program may expect and handle. Its subclasses split into checked exceptions, which the compiler forces you to catch or declare (like IOException), and unchecked ones, the RuntimeException family, which it doesn't.

That checked/unchecked split is the main topic of the next lesson. For now, know that most exceptions you'll see while learning (NullPointerException, ArithmeticException, index errors) are unchecked and come from bugs, while checked exceptions usually come from the outside world (files, networks).

Common built-in exceptions

Exception Typical cause
NullPointerException Calling a method or reading a field on null; unboxing a null Integer
ArithmeticException Integer division or remainder by zero (/ by zero)
ArrayIndexOutOfBoundsException array[i] with i < 0 or i >= length (Arrays)
StringIndexOutOfBoundsException charAt, substring with a bad index
IndexOutOfBoundsException list.get(i) with a bad index
NumberFormatException Integer.parseInt("abc"), Double.parseDouble("") (Type Casting)
ClassCastException Casting an object to a type it isn't: (String) Integer.valueOf(1)
IllegalArgumentException A method received an argument it can't accept
IllegalStateException A method was called at the wrong time (an iterator already used up, a closed resource)
UnsupportedOperationException Modifying an unmodifiable collection, such as one from List.of
ConcurrentModificationException Changing a collection while a for-each loop walks it (Iterators)
NoSuchElementException iterator.next() with nothing left, Optional.get() on an empty Optional
InputMismatchException Scanner.nextInt() meeting non-numeric input (Reading User Input)
IOException, NoSuchFileException File and network problems (checked) (Reading and Writing Files)
InterruptedException A sleeping or waiting thread was interrupted (checked) (Threads)

Here are several of them in action, each caught and described:

Java A gallery of common exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two details in the output are worth a look. List.of(1, 2, 3).get(3) reports an ArrayIndexOutOfBoundsException, a subclass of IndexOutOfBoundsException; the exact subclass is an implementation detail, so catch IndexOutOfBoundsException if you ever need to. And some exceptions have no message at all, so getMessage() returns null; never assume it's set.

Catching RuntimeException like this is fine for a demonstration. In real code, catch the specific type you expect and can handle; a broad catch also swallows bugs you didn't anticipate.

Handling or preventing?

Many unchecked exceptions are better prevented than caught. Checking if (list.isEmpty()) before computing an average is clearer and cheaper than catching ArithmeticException afterward, and if (index >= 0 && index < array.length) beats catching an index error. Catch exceptions when you can't check in advance (parsing text, reading files, talking to a server) or when the check would duplicate the work the method does anyway (trying Integer.parseInt is simpler than validating the digits yourself).

A useful pattern for user input combines both ideas: try, and on failure ask again.

Java Asking again until the input is valid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? try { IO.print("A"); int x = 5 / 0; IO.print("B"); } catch (ArithmeticException e) { IO.print("C"); } IO.print("D");

    A prints, then the division throws, so B is skipped. The catch prints C, and execution continues after the try-catch statement, printing D.
  2. 2. In a stack trace, which line shows where the exception was actually thrown?

    The top frame is the method that threw the exception. Each frame below is the caller of the one above, so main is usually near the bottom.
  3. 3. Why doesn't catch (Exception e) { } catch (NumberFormatException e) { } compile?

    A catch block also catches all subclasses of its type. Since NumberFormatException is an Exception, the compiler reports that it has already been caught. Order catch blocks from specific to general.
  4. 4. What does m() return? int m() { try { return 1; } finally { IO.println("cleanup"); } }

    try-finally without catch is legal. The return value 1 is computed, then the finally block runs and prints cleanup, then the method returns 1.
  5. 5. Which of these should ordinary application code NOT try to catch?

    StackOverflowError is an Error, signaling a serious JVM-level problem the program usually can't recover from. The others are exceptions that code can reasonably expect and handle.

Summary

  • An exception is an object describing a problem; throwing it stops the current code and propagates it up the call stack until a matching catch is found.
  • An uncaught exception prints a stack trace and ends the thread; read the trace from the top and find the first frame in your own code.
  • try { ... } catch (Type e) { ... } handles exceptions of that type and its subclasses; execution continues after the statement.
  • Several catch blocks are checked top to bottom (specific before general); multi-catch A | B shares one handler for unrelated types.
  • finally runs however the try ends, except when the JVM stops; never return from it.
  • Errors are serious JVM problems; Exceptions are checked, except the unchecked RuntimeException family.
  • Prevent bug-type exceptions with checks; catch the ones you can't predict, like parsing and I/O failures.

Next: Throwing Exceptions: throw and throws, where you'll signal problems from your own methods and learn checked versus unchecked exceptions.