01 / 20

Throwing
Exceptions in Java

Learn how to intentionally throw exceptions to guard against invalid states, enforce preconditions, and write robust, self-defending code.

Java

What is an Exception?

An exception is an event that disrupts the normal flow of a program. In Java, exceptions are objects: they carry information about what went wrong, where it happened, and why.

Object
Every exception is an instance of a class that extends Throwable.
Signal
Exceptions signal that something unexpected or invalid has occurred.
Recoverable
Callers can catch exceptions and decide how to handle the problem.

Why Throw Exceptions?

Without exceptions, invalid inputs silently produce garbage output or crash later in confusing ways. Throwing exceptions early makes bugs visible the moment they happen.

Without throw
\( \text{age} = -5 \) (invalid!)
silently continues Crash 200 lines later Hard to debug With throw
\( \text{age} = -5 \) (invalid!)
Exception thrown NOW Caught immediately

The Exception Hierarchy

Throwable Error OutOfMemoryError StackOverflowError Exception RuntimeException IllegalArgumentException IllegalStateException NullPointerException Checked IOException SQLException You will mostly throw RuntimeException subtypes

The throw Keyword

The throw keyword creates and launches an exception object. Execution immediately stops at that line and jumps to the nearest matching catch block (or terminates the program).

throw new IllegalArgumentException("Age cannot be negative");

throw vs throws

throw throws
What it does Actually launches an exception Declares that a method might throw one
Where it goes Inside the method body In the method signature
Followed by An exception object An exception class name
Example throw new E() void m() throws E

Common Exception Types to Throw

IllegalArgumentException
A parameter value is invalid: negative age, null name, empty string.
IllegalStateException
The object is not in the right state for the operation: withdrawing from a closed account.
NullPointerException
A required reference is null when it must not be. Often thrown via Objects.requireNonNull.

The Guard Pattern

A guard clause validates input at the top of a method and throws an exception if the precondition fails. This keeps the "happy path" clean and unindented.

Method called Valid? NO throw YES Execute logic return

How to Apply It

1
Identify preconditions. What must be true about the parameters for your method to work correctly?
2
Write an if-check. Test whether the precondition is violated (the negative condition).
3
Choose the exception type. Bad argument: IllegalArgumentException. Bad state: IllegalStateException.
4
Include a clear message. Describe what was wrong and what was expected, e.g., "Age must be non-negative, got: -5".
5
Place the guard at the top of the method, before any logic runs.

Example 1: Validating Age

public void setAge(int age) { if (age < 0) { throw new IllegalArgumentException( "Age must be non-negative, got: " + age ); } this.age = age; }

Example 2: Null Guard

public void setName(String name) { if (name == null) { throw new NullPointerException( "Name must not be null" ); } if (name.isEmpty()) { throw new IllegalArgumentException( "Name must not be empty" ); } this.name = name; }

Example 3: State Validation

public class BankAccount { private double balance; private boolean closed = false; public void withdraw(double amount) { if (closed) { throw new IllegalStateException( "Account is closed" ); } if (amount <= 0) { throw new IllegalArgumentException( "Amount must be positive" ); } if (amount > balance) { throw new IllegalArgumentException( "Insufficient funds" ); } balance -= amount; } }

Anatomy of Multiple Guards

The withdraw method has three guard clauses at the top, each defending a different precondition. Only after all checks pass does the actual logic run.

1
State guard: is the account closed? If yes, throw IllegalStateException.
2
Argument guard: is the amount \( \leq 0 \)? If yes, throw IllegalArgumentException.
3
Business rule guard: is amount \( > \text{balance} \)? If yes, throw IllegalArgumentException.

Common Mistakes

Vague Messages
Writing "Invalid input" instead of explaining what was wrong and what was expected.
Wrong Exception Type
Using Exception or RuntimeException directly instead of a specific subclass like IllegalArgumentException.
Forgetting new
Writing throw IllegalArgumentException(...) without new. You must create an object before throwing it.

Exception Cheat Sheet

Scenario Exception Type Example Message
Negative number IllegalArgumentException "Value must be \( \geq 0 \)"
Null reference NullPointerException "Name must not be null"
Out of range IndexOutOfBoundsException "Index 5 out of range [0..3]"
Object not ready IllegalStateException "Connection is closed"
Unsupported call UnsupportedOperationException "Read-only list"

Question 1 of 5

Which keyword is used to actually launch an exception object in Java?

Question 2 of 5

A method receives an age parameter of -3. Which exception type is most appropriate to throw?

Question 3 of 5

This code has a compile-time error. What is wrong?

Question 4 of 5

You are writing a withdraw method for a bank account that has already been closed. Which exception type should you throw?

Question 5 of 5

Where should guard clauses (throw statements for invalid input) be placed inside a method?