Throwing
Exceptions in Java
Learn how to intentionally throw exceptions to guard against invalid states, enforce preconditions, and write robust, self-defending code.
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.
Throwable.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.
The Exception Hierarchy
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 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
IllegalArgumentExceptionIllegalStateExceptionNullPointerExceptionObjects.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.
How to Apply It
IllegalArgumentException. Bad state: IllegalStateException."Age must be non-negative, got: -5".Example 1: Validating Age
Example 2: Null Guard
Example 3: State Validation
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.
IllegalStateException.IllegalArgumentException.IllegalArgumentException.Common Mistakes
Exception or RuntimeException directly instead of a specific subclass like IllegalArgumentException.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
Consider this code:
public void setScore(int score) {
if (score < 0 || score > 100) {
throw IllegalArgumentException("Bad score");
}
this.score = score;
}
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?