Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 201 ยท Exceptions

Throwing Exceptions: throw and throws

Learn to throw exceptions in Java - the throw statement, the throws clause, checked vs unchecked exceptions, the Throwable hierarchy, choosing exception types and rethrowing.

In the previous lesson you caught exceptions thrown by the JDK. Your own methods need the same power. When a method receives an argument it can't work with, or is asked to do something that's impossible right now, the honest response is not to return a made-up value or print a warning and carry on. It's to throw an exception: stop immediately and tell the caller precisely what went wrong.

Java has two related keywords for this. throw (a statement) actually throws an exception object. throws (part of a method signature) declares that a method may let certain exceptions escape to its caller. Understanding them means understanding Java's split between checked and unchecked exceptions, one of the language's most distinctive features. This lesson covers both keywords, the full Throwable hierarchy, how to pick the right exception type and message, the rules for overriding, checked exceptions in lambdas, and rethrowing.

The throw statement

throw takes any object whose class extends Throwable, usually a newly created one:

Java
throw new IllegalArgumentException("age must not be negative: " + age);

The effect is the same as when the JDK throws: the current method stops at once, nothing after the throw runs, and the exception propagates up the call stack until something catches it.

Java Validating arguments with throw

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.

This style is called failing fast: check the inputs at the top of the method, throw as soon as something is wrong, and the rest of the method can trust its data. A bug caught at the boundary, with a message naming the bad value, is far easier to fix than a wrong number discovered three screens later.

throw is a statement the compiler understands

The compiler knows that throw never completes normally, which has some useful consequences:

  • Code directly after a throw in the same block is unreachable, a compile error.
  • A method with a return type doesn't need a return after a throw: default: throw new IllegalStateException(...) satisfies the compiler.
  • In a switch expression, an arm can throw instead of producing a value: case 0 -> throw new ArithmeticException("no zero").

Choosing the right exception

Before inventing a new exception class, check whether a standard one fits. Other developers already know what they mean:

Exception Throw it when
IllegalArgumentException An argument has an invalid value (negative size, empty name, unknown code)
IllegalStateException The arguments are fine, but the object isn't in a state to do this (withdrawing from a closed account, reading after close())
NullPointerException An argument is null but mustn't be; usually via Objects.requireNonNull
IndexOutOfBoundsException An index argument is out of range; usually via Objects.checkIndex
UnsupportedOperationException The object doesn't support this operation at all (a read-only view's add)
ArithmeticException A calculation is mathematically impossible
NoSuchElementException Something was requested that doesn't exist (the next element, a missing entry)

java.util.Objects has helpers that throw the standard exceptions with good messages:

Java Objects.requireNonNull and checkIndex

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.

Writing a good message

The message is for the developer who reads a stack trace at 2 a.m. Make it specific:

  • Include the bad value: "quantity must be positive, was -3" beats "invalid quantity".
  • Say what was expected: "month must be 1-12".
  • Don't include secrets: passwords, tokens and full card numbers end up in logs.
  • Keep it a plain fact, not advice for end users. Turning an exception into a friendly message is the job of the code that catches it, closer to the user interface.

Checked and unchecked exceptions

Here is the full family tree again, with the distinction that matters for this lesson:

TEXT
Throwable                         checked
โ”œโ”€โ”€ Error                         unchecked: JVM problems
โ””โ”€โ”€ Exception                     checked
    โ”œโ”€โ”€ IOException               checked
    โ”‚   โ”œโ”€โ”€ FileNotFoundException
    โ”‚   โ””โ”€โ”€ NoSuchFileException   (in java.nio.file, via FileSystemException)
    โ”œโ”€โ”€ InterruptedException      checked
    โ”œโ”€โ”€ TimeoutException          checked
    โ”œโ”€โ”€ ...
    โ””โ”€โ”€ RuntimeException          unchecked
        โ”œโ”€โ”€ IllegalArgumentException
        โ”œโ”€โ”€ IllegalStateException
        โ”œโ”€โ”€ NullPointerException
        โ””โ”€โ”€ ...
  • Unchecked exceptions are RuntimeException, Error and all their subclasses. The compiler doesn't track them. They typically signal programming errors (a null where it mustn't be, a bad index) or invalid arguments, conditions the caller could have avoided.
  • Checked exceptions are everything else: Exception and its subclasses outside the RuntimeException branch. They signal problems from the outside world that even correct code can't rule out: a file was deleted, a network is down, a thread was interrupted.

For checked exceptions, the compiler enforces the catch-or-declare rule: any code that can throw a checked exception must either catch it or declare it with throws. This example fails to compile on purpose:

Java The catch-or-declare rule (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 compiler stops with unreported exception IOException; must be caught or declared to be thrown. Files.readString declares throws IOException, so any caller must deal with it. You have exactly two options, shown next.

The throws clause

To declare that a method lets an exception escape, add throws after the parameter list. Several types are separated by commas:

Java
String loadConfig() throws IOException { ... }
void transfer(Account from, Account to) throws InsufficientFundsException, AccountLockedException { ... }

Now the obligation moves to the callers: each one must catch the exception or declare it in turn. Somewhere up the chain, a method that can actually do something about the problem (show an error, use a default, retry) catches it.

Java Declaring and catching a checked exception

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.

Notes on this example:

  • NoSuchFileException is a subclass of IOException, so it's caught first, with its own handling; other I/O problems fall into the general block.
  • main may declare throws too. If an exception escapes main, the program prints the stack trace and exits with status 1. That's acceptable for small tools and examples, not for real applications.
  • You can declare unchecked exceptions in throws as documentation (throws IllegalArgumentException), but the compiler doesn't require it. The better place to document them is a Javadoc @throws tag (Comments and Javadoc):
Java
/**
 * Withdraws money from the account.
 *
 * @param amount the amount in cents; must be positive
 * @throws IllegalArgumentException if amount is zero or negative
 * @throws IllegalStateException if the account is closed
 */
void withdraw(long amount) { ... }

throws and overriding

An overriding method may throw fewer or narrower checked exceptions than the method it overrides, never new or broader ones. Code that calls the method through the parent type only prepared for the parent's exceptions:

Java
interface Loader {
    String load(String name) throws IOException;
}

class FileLoader implements Loader {
    public String load(String name) throws NoSuchFileException { ... }   // OK: narrower
}

class MemoryLoader implements Loader {
    public String load(String name) { ... }                              // OK: throws nothing
}

class BrokenLoader implements Loader {
    public String load(String name) throws Exception { ... }             // error
}

The last one fails with load(String) in BrokenLoader cannot implement load(String) in Loader and the note overridden method does not throw Exception. Unchecked exceptions are unaffected: any method may throw them. This rule is part of the overriding rules in Polymorphism and Method Overriding.

Checked exceptions and lambdas

The standard functional interfaces (Function, Consumer, Supplier...) declare no checked exceptions, so a lambda body that throws one doesn't compile. The usual solution is to catch the checked exception inside the lambda and wrap it in an unchecked one. For I/O, the JDK has a ready-made wrapper, UncheckedIOException:

Java Wrapping a checked exception inside a lambda

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 original exception travels along as the cause, so no information is lost: getCause() returns it, and a stack trace shows it under Caused by:. You'll build your own wrapper exceptions in Custom Exceptions.

Are checked exceptions a good idea?

Java is nearly alone among popular languages in having them, and the debate is old. In their favor: the compiler makes sure you think about failures that will happen in production, like missing files. Against them: they add boilerplate, they don't work with lambdas, and they tempt people into empty catch blocks just to silence the compiler, which is worse than no handling at all.

The practical consensus in modern Java:

  • Use unchecked exceptions for programming errors and invalid arguments (the IllegalArgumentException family).
  • Use checked exceptions only when the caller can reasonably be expected to recover, and the condition isn't a bug: a missing file the user chose, a payment declined by the bank.
  • Many modern libraries and frameworks (including Spring and most JSON libraries) use unchecked exceptions almost exclusively. When in doubt, choose unchecked.

Rethrowing exceptions

Sometimes a method catches an exception to do something with it (record it, add context, clean up) and then lets it continue. That's rethrowing:

Java
try {
    processOrder(order);
} catch (PaymentException e) {
    audit.recordFailure(order, e);   // do our part...
    throw e;                         // ...and let the caller handle the rest
}

Rethrowing the same object keeps its original stack trace, which still points to where the problem happened.

Java also performs precise rethrow: if you catch a broad type but the variable is never reassigned, the compiler knows which checked exceptions the try block can really throw, and only those need to be declared:

Java Precise rethrow

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.

Without precise rethrow, fetchWithLog would have to declare throws Exception, forcing every caller to handle any exception. It stops working if you assign to e in the catch block, which is one more reason never to do that.

Rethrow, wrap or handle?

When an exception reaches your method, you have three honest choices:

  1. Handle it if you can actually fix the situation: use a default, retry, ask the user again.
  2. Let it propagate (declare it, or just don't catch an unchecked one) if a caller is better placed to decide. This is the right choice more often than beginners think.
  3. Wrap it in a different exception if the original type would leak implementation details: a UserRepository shouldn't make its callers deal with SQLException. That's exception translation, covered in Custom Exceptions.

The wrong choice is a fourth one: catching and doing nothing. An empty catch block hides the problem and leaves the program running in a broken state. Exception Handling Best Practices collects the rules.

Exceptions are relatively expensive to create, mainly because the JVM records the stack trace. That doesn't matter for real errors, but don't use exceptions for ordinary control flow, such as ending a loop or returning a "not found" result from a lookup that misses often. Return Optional (Optional) or a boolean instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these is a checked exception?

    IOException extends Exception but not RuntimeException, so it's checked. The other three are subclasses of RuntimeException and therefore unchecked.
  2. 2. A method calls Thread.sleep(100) (which throws the checked InterruptedException) and has no try-catch. What must its signature include to compile?

    Under the catch-or-declare rule, an uncaught checked exception must be declared with throws in the method signature. throw (without s) is the statement that throws an object.
  3. 3. An interface method is declared void save() throws IOException. Which implementation does NOT compile?

    An overriding method may throw fewer or narrower checked exceptions, and any unchecked ones, but not broader checked exceptions such as Exception.
  4. 4. A deposit method receives a negative amount. Which exception fits best?

    The problem is the argument's value, so IllegalArgumentException is the standard choice. IllegalStateException is for a valid call made at the wrong time, such as depositing into a closed account.
  5. 5. Why wrap an IOException in UncheckedIOException inside a lambda passed to map?

    Standard functional interfaces don't declare checked exceptions. Wrapping converts the problem into an unchecked exception while preserving the original through getCause().

Summary

  • throw new SomeException("message") stops the method and propagates the exception; validate arguments at the top of a method and fail fast.
  • Prefer standard exceptions: IllegalArgumentException for bad values, IllegalStateException for wrong timing, Objects.requireNonNull and Objects.checkIndex for nulls and indexes. Put the bad value in the message.
  • Unchecked exceptions (RuntimeException, Error and subclasses) aren't tracked by the compiler; all other exceptions are checked and follow the catch-or-declare rule.
  • throws in a signature declares checked exceptions a method lets escape; overriding methods may only narrow them.
  • Lambdas can't throw checked exceptions through standard functional interfaces; wrap them (for I/O, in UncheckedIOException).
  • throw e; rethrows with the original stack trace; precise rethrow lets you catch broadly but declare narrowly.
  • For each exception: handle it, let it propagate, or wrap it. Never swallow it.

Next: Custom Exceptions, where you'll design your own exception classes with messages, causes and chaining.