Throwing Exceptions and Creating Custom Exception Classes in Java
Learn how to throw exceptions in Java with the throw statement, pick the right standard exception, write your own checked or unchecked exception classes with the four conventional constructors, and attach extra data and causes.
kvi5hnuCode Sprout team member10 min readOn this page
The previous article showed where exceptions come from in the class hierarchy and when a method must declare them. This one is about your side of the deal: raising an exception when your code finds something it cannot deal with, and designing exception classes of your own when none of the standard ones describe the problem well.
When should a method throw?
A method throws an exception when it cannot finish its job and returning a normal value would be a lie. Some typical cases:
- The input breaks the method's contract, such as a negative amount or a
nullname. - The object is in the wrong state for the request, such as withdrawing from a closed account.
- Something outside the program failed, such as a file ending before the data it promised.
Suppose a method readData reads a file whose header says Content-length: 1024, and the file ends after 733 characters. That is abnormal: the header made a promise the data didn't keep. The method can't return a sensible string, so it should throw.
Which exception? Search the standard library for one that matches. The IOException family has a subclass described as "Signals that an end of file or end of stream has been reached unexpectedly during input." That is exactly our situation: java.io.EOFException.
The throw statement
Throwing takes one line:
throw new EOFException();
or, split up:
var e = new EOFException();
throw e;
In the context of a method, it looks like this:
String readData(Scanner in) throws EOFException {
. . .
while (. . .) {
if (!in.hasNext()) { // EOF encountered
if (n < len)
throw new EOFException();
}
. . .
}
return s;
}
Most exception classes also have a constructor that takes a message. Use it. A good message says what was expected and what actually happened, which turns a vague stack trace into a quick fix:
String gripe = "Content-length: " + len + ", Received: " + n;
throw new EOFException(gripe);
So throwing an existing exception class comes down to three steps:
- Find an appropriate exception class.
- Make an object of that class, ideally with a helpful message.
- Throw it.
Once a method throws, it does not return to its caller. There is no return value, and you don't need to worry about producing one. The runtime starts looking for a handler instead, walking back up the call stack:

Each method on the way up either has a matching catch clause or exits too. The next article covers catching in detail.
Prefer the standard exceptions
Before writing a new class, check whether the JDK already has one that fits. Programmers who read your code recognize these at a glance, and they come with the right checked or unchecked status:
| Situation | Exception | Kind |
|---|---|---|
| An argument has an illegal value | IllegalArgumentException | unchecked |
| The object is in the wrong state for this call | IllegalStateException | unchecked |
A required argument is null | NullPointerException, usually via Objects.requireNonNull(x, "message") | unchecked |
| An index is out of range | IndexOutOfBoundsException, usually via Objects.checkIndex(i, length) | unchecked |
The operation isn't supported by this object, such as add on an immutable list | UnsupportedOperationException | unchecked |
| There is no next element, or no value present | NoSuchElementException | unchecked |
| A number has the wrong format | NumberFormatException (subclass of IllegalArgumentException) | unchecked |
| A string has the wrong format for a date or time | DateTimeParseException | unchecked |
| Input or output failed | IOException and subclasses such as EOFException, FileNotFoundException, NoSuchFileException | checked |
| An operation timed out | TimeoutException | checked |
| A thread was interrupted while waiting | InterruptedException | checked |
Never throw Exception, RuntimeException, Throwable or Error themselves. They say nothing specific, so callers can only catch them by catching everything. Error subclasses are reserved for the virtual machine.
Creating your own exception classes
Sometimes no standard class describes the problem well. Then you write your own, by extending Exception or one of its subclasses. Which superclass you pick decides whether the exception is checked:
- Extend
Exception, or a checked subclass likeIOException, for a checked exception. Callers must handle or declare it. - Extend
RuntimeException, or a subclass likeIllegalStateException, for an unchecked exception. Callers may ignore it.
Pick the most meaningful parent. A malformed file is an I/O problem, so a FileFormatException fits nicely under IOException. Code that already catches IOException then handles it automatically.
By convention, an exception class has a no-argument constructor and a constructor that takes a detail message. The superclass Throwable stores the message, and its toString method prints it after the class name, which is handy in logs and debugging. Modern code usually supplies the two cause constructors too, for wrapping a lower-level exception (more on chaining in the next article). So the full set is:
class FileFormatException extends IOException {
private static final long serialVersionUID = 1L;
public FileFormatException() { }
public FileFormatException(String gripe) { super(gripe); }
public FileFormatException(String gripe, Throwable cause) { super(gripe, cause); }
public FileFormatException(Throwable cause) { super(cause); }
}
Now you can throw your own exception type exactly like a library one:
String readData(Scanner in) throws FileFormatException {
. . .
while (. . .) {
if (ch == -1) { // EOF encountered
if (n < len)
throw new FileFormatException();
}
. . .
}
return s;
}
Carrying extra information
An exception is an ordinary object, so it can have fields. If a caller may want to react to details of the failure, store them in final fields with getters instead of forcing callers to parse the message:
class InsufficientFundsException extends Exception {
private static final long serialVersionUID = 1L;
private final double shortfall;
public InsufficientFundsException(String message, double shortfall, Throwable cause) {
super(message, cause);
this.shortfall = shortfall;
}
public double getShortfall() { return shortfall; }
}
Keep exceptions immutable: they are often logged, rethrown and passed between threads.
Checked or unchecked?
There is no rule that fits every project, but these questions help:
- Can a reasonable caller recover? If the caller can retry, ask the user for another file, or fall back to a default, a checked exception reminds them to plan for it.
- Is it a bug in the caller? A
nullargument or a negative quantity should be fixed in code, not handled at run time. Use an unchecked exception. - Will it pass through lambdas? The functional interfaces in
java.util.functiondon't declare checked exceptions, so a checked exception can't escape a lambda passed tomaporforEach. Libraries meant for stream-heavy code often choose unchecked exceptions for this reason.
Many modern frameworks use unchecked exceptions almost exclusively. The JDK itself mixes both. What matters most is consistency within one codebase.
The Throwable API you just used
The methods that matter when you create and throw exceptions:
| Member | Purpose |
|---|---|
Throwable() | Makes an exception with no detail message |
Throwable(String message) | Makes an exception with a detail message |
Throwable(String message, Throwable cause) | Adds the underlying cause |
Throwable(Throwable cause) | Uses the cause, and its toString, as the message |
String getMessage() | Returns the detail message, or null if there is none |
Throwable getCause() | Returns the cause, or null |
String toString() | The class name, followed by ": " and the message if there is one |
A complete example
The program below:
- parses a tiny "file" format with a
Content-lengthheader and throwsEOFExceptionor our ownFileFormatException; - guards a method with
IllegalArgumentExceptionandIllegalStateException; - uses
requireNonNullandcheckIndex; - throws a domain exception that carries data and a cause;
- ends a switch arm with
throw.
import java.io.EOFException;
import java.io.IOException;
import java.util.*;
public class Solution {
public static void main(String[] args) {
// a header promises 12 characters, but the data stops early
for (String input : List.of("Content-length: 12\nHello, World", "Content-length: 12\nHello", "Length 12\nHi")) {
try {
System.out.println("read: " + readData(new Scanner(input)));
} catch (FileFormatException e) {
System.out.println("format problem: " + e.getMessage());
} catch (EOFException e) {
System.out.println("EOF: " + e.getMessage());
}
}
// standard unchecked exceptions for programming errors
var account = new Account(100);
try {
account.withdraw(-5);
} catch (IllegalArgumentException e) {
System.out.println(e); // toString: class name + message
}
account.close();
try {
account.withdraw(10);
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
try {
Objects.requireNonNull(null, "owner must not be null");
} catch (NullPointerException e) {
System.out.println("NPE: " + e.getMessage());
}
try {
Objects.checkIndex(5, 3);
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
// a domain exception with extra data, and a cause
try {
new Bank().transfer("ACC-1", "ACC-2", 250);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage() + " (short by " + e.getShortfall() + ")");
System.out.println("cause: " + e.getCause());
}
// throw is an expression-like statement: it can end a switch arm
System.out.println(dayType(6));
try {
dayType(9);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
static String readData(Scanner in) throws EOFException, FileFormatException {
String header = in.nextLine();
if (!header.startsWith("Content-length: "))
throw new FileFormatException("Missing header: " + header);
int len = Integer.parseInt(header.substring("Content-length: ".length()));
var s = new StringBuilder();
int n = 0;
while (n < len) {
if (!in.hasNextLine()) { // EOF encountered
String gripe = "Content-length: " + len + ", Received: " + n;
throw new EOFException(gripe);
}
String line = in.nextLine();
s.append(line);
n += line.length();
}
return s.toString();
}
static String dayType(int day) {
return switch (day) {
case 1, 2, 3, 4, 5 -> "weekday";
case 6, 7 -> "weekend";
default -> throw new IllegalArgumentException("No such day: " + day);
};
}
}
/** A checked exception for malformed input files. */
class FileFormatException extends IOException {
private static final long serialVersionUID = 1L; // exceptions are Serializable
public FileFormatException() { }
public FileFormatException(String gripe) { super(gripe); }
public FileFormatException(String gripe, Throwable cause) { super(gripe, cause); }
public FileFormatException(Throwable cause) { super(cause); }
}
/** A checked domain exception that carries extra information. */
class InsufficientFundsException extends Exception {
private static final long serialVersionUID = 1L;
private final double shortfall;
public InsufficientFundsException(String message, double shortfall, Throwable cause) {
super(message, cause);
this.shortfall = shortfall;
}
public double getShortfall() { return shortfall; }
}
class Account {
private double balance;
private boolean closed;
Account(double balance) { this.balance = balance; }
void withdraw(double amount) {
if (amount <= 0) throw new IllegalArgumentException("amount must be positive: " + amount);
if (closed) throw new IllegalStateException("account is closed");
balance -= amount;
}
void close() { closed = true; }
}
class Bank {
void transfer(String from, String to, double amount) throws InsufficientFundsException {
double balance = 100;
if (amount > balance)
throw new InsufficientFundsException("Cannot transfer " + amount + " from " + from,
amount - balance, new IllegalStateException("balance check failed"));
}
}
read: Hello, World
EOF: Content-length: 12, Received: 5
format problem: Missing header: Length 12
java.lang.IllegalArgumentException: amount must be positive: -5.0
account is closed
NPE: owner must not be null
Index 5 out of bounds for length 3
Cannot transfer 250.0 from ACC-1 (short by 150.0)
cause: java.lang.IllegalStateException: balance check failed
weekend
No such day: 9
Notice that System.out.println(e) printed the class name and then the message. That's Throwable.toString at work. getMessage alone gives just the message.
Common questions
Should my custom exception be checked or unchecked? Make it unchecked when it signals a bug or a condition that callers can't reasonably handle, and checked when a caller is expected to recover, for example by retrying or asking for other input. Many modern codebases default to unchecked exceptions. Consistency within one project matters more than the choice.
What makes a good exception message?
State what was expected, what was found, and the identifying data: "Expected 1024 bytes but file ended after 733 (file: orders.dat)". Never include passwords or personal data, because messages end up in logs. Don't end messages with a period or start them with "Error:", since the exception type already says that.
Is creating exceptions expensive?
Filling in the stack trace costs time, especially in deep call stacks. That's irrelevant for real failures, but it's a reason not to use exceptions for normal control flow such as ending loops. In very rare high-performance cases, an exception class can disable stack traces through the protected four-argument Throwable constructor.
Should I throw IllegalArgumentException or NullPointerException for a null argument?
The JDK convention is NullPointerException (via Objects.requireNonNull), and IllegalArgumentException for other invalid values. Whichever you choose, document it with @throws and use it consistently.
Can a record be an exception?
No. Records can't extend classes, and exceptions must extend Throwable. Write a regular final class with final fields and getters. The fields of an exception should still be immutable.
Summary
- Throw an exception when a method can't complete its job:
throw new SomeException("message");. The method exits immediately and returns no value. - Write messages that state what was expected and what happened.
- Java can only throw objects whose class extends
Throwable. - Prefer standard exceptions:
IllegalArgumentException,IllegalStateException,UnsupportedOperationException,NoSuchElementException, plusObjects.requireNonNullandObjects.checkIndex. - For your own exceptions, extend
Exception(or a checked subclass) for checked, orRuntimeExceptionfor unchecked. Choose the most meaningful parent. - Provide the conventional constructors: none, message, message plus cause, cause. Add a
serialVersionUID. - Put extra data in immutable fields with getters rather than in the message only.
Practice Questions
What happens to the rest of a method after a throw statement runs?
Nothing more of it runs. The method exits immediately and doesn't return a value. The runtime then looks for a matching handler in the callers, unwinding the call stack until one is found.
Why does a switch expression accept a default arm that only throws?
A switch expression must produce a value on every path that completes normally. A throw never completes normally, so that arm needs no value.
You are writing a class for parsing a configuration file. A line has the wrong syntax. Which superclass would you choose for a custom exception, and why?
IOException is a good fit if the problem is reported while reading a file: callers that already handle I/O errors handle it too, and it stays checked. If configuration errors are considered programming or deployment mistakes that no caller can fix, an unchecked exception extending RuntimeException or IllegalArgumentException is defensible. Either way, be consistent within the project.
What does toString print for new FileFormatException("bad header")? And for new FileFormatException()?
FileFormatException: bad header (with the package prefix if the class is in a package), and just FileFormatException when there is no message.
Why is it better to store the shortfall in a field than to put it only in the message?
Callers can then read it with getShortfall() and react, for example by offering a smaller transfer. Parsing a number out of a message is fragile and breaks when someone rewords the text.
Is it a good idea to throw new RuntimeException("something failed")?
Usually not. It tells callers nothing specific, so they can't catch it without catching every unchecked exception. Use a precise standard exception or define your own.
Previous: Java Exceptions: The Exception Hierarchy, Checked and Unchecked
Next: Catching Exceptions in Java: try/catch, Multi-catch, Rethrowing and Chaining
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.