skip to content

throw Statement

throw transfers control immediately and unwinds the current method, and it requires a real Throwable — throwing null gives you a NullPointerException instead. A small detail that occasionally appears as a puzzle.

part ofJavaoverview, primer and where to startread it →
on this pageshow

questions

5

What does the throw statement do in Java, and what must follow the throw keyword?

level: juniorimportance: must knowfreq 75%

answer

  1. throw <Throwable> — must be Throwable or subtype
  2. stops normal flow immediately, then unwinds
  3. finally still runs while unwinding
  4. propagates up the call stack if uncaught
  5. usually throw new SomeException("msg")

basics

~20 s

throw raises an exception. After the keyword you put an object that is a Throwable (an Exception or Error). Once thrown, the current method stops normal execution and control jumps to a matching catch block, or out of the method if none catches it.

solid answer

~40 s

The throw statement explicitly raises an exception. Its syntax is throw <expression>, where the expression must evaluate to a reference of type Throwable or a subtype (Exception, RuntimeException, Error, or your own subclass). When throw executes, normal flow stops immediately: Java looks for an enclosing try/catch that handles that type, running any finally blocks as it unwinds. If no handler is found in the method, the exception propagates to the caller, and so on up the call stack until handled or the thread terminates. You usually throw a freshly constructed exception, e.g. throw new IllegalArgumentException("x must be positive"), but you can also re-throw a caught one.

code

java · 9 lines
java
int withdraw(int balance, int amount) {
    if (amount <= 0) {
        throw new IllegalArgumentException("amount must be positive");
    }
    if (amount > balance) {
        throw new IllegalStateException("insufficient funds");
    }
    return balance - amount; // only reached when no throw fired
}

go deeper

for a junior

States throw raises an exception, the operand must be a Throwable, and execution stops and jumps to a catch.

for a middle

Explains stack unwinding, finally running during unwind, and the difference between constructing and re-throwing.

for a senior

Discusses propagation semantics, unreachable-code compile errors, and when to throw vs. let the JVM raise an exception.

for a principal

Frames throw within an API's failure contract and exception-design strategy across a codebase.

## What "throwing" means In Java, an **exception** is an object that represents an abnormal situation (bad input, missing file, programming bug). The normal way these objects come into existence as live errors is the **throw statement**. Until you throw it, an exception object is just an ordinary object sitting in memory; `throw` is what turns it into an *active* error that interrupts the program. ## The syntax and the type rule The statement is simply: ``` throw expression; ``` The `expression` must produce a reference whose type is **`Throwable`** or any subclass of it. `Throwable` is the root of Java's whole error hierarchy. Its two direct children are: - **`Error`** — serious problems the application normally should not catch (e.g. `OutOfMemoryError`). - **`Exception`** — recoverable conditions. Under `Exception` sits **`RuntimeException`** (the *unchecked* family: `NullPointerException`, `IllegalArgumentException`, etc.). If you write `throw 5;` or `throw "oops";` the code will **not compile**, because `int` and `String` are not `Throwable`. The compiler enforces the type rule. ## What happens at runtime When `throw` executes: 1. **Normal execution stops at that exact point.** No statement after the `throw` in that block runs. 2. The Java runtime searches outward for an enclosing `try` block whose `catch` can handle the thrown type (a catch matches if the thrown object is an instance of the caught type). 3. As it leaves each block on the way out, any associated **`finally`** block runs (cleanup still happens). 4. If the current method has no matching handler, the exception **propagates** to the method's caller. This repeats up the **call stack**. 5. If it reaches the top of the thread with no handler, the thread's default handler prints the stack trace and the thread ends. ## Constructing vs. re-throwing Most of the time you throw a newly built object so it carries a useful message: ```java if (amount < 0) { throw new IllegalArgumentException("amount must be >= 0, was " + amount); } ``` But `throw` works on any `Throwable` reference, so you can also catch one and re-throw it (optionally after logging or wrapping it in another exception). ## Why it matters `throw` is the deliberate, programmer-controlled way to signal failure — as opposed to exceptions the JVM raises automatically (like dividing by zero). It lets a method refuse to continue with bad data and hand the problem to code better positioned to deal with it.

  • Can you throw a String or an int?
    No. The operand of throw must be a Throwable (or subclass). String and int are not Throwable, so the code fails to compile.
  • What happens to code written after a throw in the same block?
    It never executes; in fact, code that is unreachable because it directly follows an unconditional throw causes a compile error ('unreachable statement').

Throwing is like pulling a fire alarm: the moment you pull it, everyone stops what they're doing and the building empties floor by floor (the call stack) until someone responsible (a catch block) takes charge — or everyone evacuates the building (the thread dies).

saying these in an interview costs you the question

  • Thinking throw can raise any object (it must be a Throwable)
  • Believing finally is skipped when an exception is thrown
  • Confusing throw (raise one now) with throws (declare what a method may raise)
  • Assuming statements after throw still run

context

open as a page

What is the difference between `throw` and `throws` in Java?

level: juniorimportance: must knowfreq 68%

basics

~20 s

throw is a statement that raises one exception right now inside a method body. throws is part of a method's signature that declares which checked exceptions the method might pass to its caller. One acts; the other warns.

open as a page

What happens when you write `throw null;` in Java, and why?

level: middleimportance: should knowfreq 55%

basics

~10 s

throw null compiles, but at runtime Java cannot raise a null exception, so it throws a NullPointerException instead. The same thing happens if a variable you throw happens to be null.

open as a page

How do you re-throw a caught exception, and what is the difference between re-throwing as-is and wrapping it in a new exception?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Inside a catch block you can throw the same exception again to let it keep propagating, or you can throw a new exception that includes the original as its 'cause'. Wrapping lets you raise a more meaningful exception while preserving the original stack trace.

open as a page

How does the throw statement interact with definite-assignment and unreachable-code analysis at compile time?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

Because throw never lets execution continue past it, the compiler treats code right after an unconditional throw as unreachable, which is a compile error. It also means a method ending in throw doesn't need a return, and branches that always throw count as completing for assignment checks.

open as a page