01 / 21

Custom Exceptions
in Java

Learn how to design and implement your own exception classes to create more meaningful, descriptive error handling in Java applications.

Java

What Is an Exception?

An exception is an event that disrupts the normal flow of a program. When something goes wrong at runtime: a file is missing, a number is divided by zero, or invalid input is received: Java creates an exception object describing the error.

The Exception Hierarchy

Throwable Error Exception IOException (checked) RuntimeException (unchecked) YourCustomException extends Exception Don't catch/extend these (Error subclasses)

Why Create Custom Exceptions?

Clarity
A InsufficientFundsException is far more descriptive than a generic Exception with a message string.
Targeted Catching
Callers can write separate catch blocks for each exception type, handling each error differently.
Extra Data
Custom exceptions can carry domain-specific fields like errorCode, amount, or userId.

Checked vs Unchecked Exceptions

Checked Unchecked
Extends Exception RuntimeException
Compiler enforces Yes: must catch or declare No: optional handling
Use when Recoverable conditions Programming errors / bugs
Example InvalidEmailException NegativeAmountException

The Core Pattern

public class MyException extends Exception { // No-argument constructor public MyException() { super(); } // Constructor with a message public MyException(String message) { super(message); } // Constructor with message + cause public MyException(String message, Throwable cause) { super(message, cause); } }

Extending Exception vs RuntimeException

Checked (extends Exception) Compiler forces you to handle it Must use try/catch or throws InvalidAgeException InsufficientFundsException FileParseException Unchecked (extends RuntimeException) No compiler enforcement Optional handling NegativePriceException InvalidConfigException DuplicateEntryException vs

How to Create a Custom Exception

1
Choose your parent class. Extend Exception for checked or RuntimeException for unchecked.
2
Name it descriptively. Use the pattern [Problem]Exception: InsufficientFundsException, InvalidEmailException.
3
Add constructors. At minimum: a no-arg constructor and one that takes a String message. Call super(...) in each.
4
Add custom fields (optional). Store domain data like errorCode or invalidValue with getters.
5
Throw it where the error occurs using throw new YourException("message").

Example 1: InvalidAgeException

public class InvalidAgeException extends Exception { public InvalidAgeException(String message) { super(message); } }
public class Validator { public static void checkAge(int age) throws InvalidAgeException { if (age < 0 || age > 150) { throw new InvalidAgeException("Age must be 0-150, got: " + age); } } }

Example 2: Adding Custom Fields

public class InsufficientFundsException extends Exception { private final double deficit; public InsufficientFundsException(double deficit) { super("Short by $" + deficit); this.deficit = deficit; } public double getDeficit() { return deficit; } }

Example 3: Using It in Practice

public class BankAccount { private double balance; public void withdraw(double amount) throws InsufficientFundsException { if (amount > balance) { throw new InsufficientFundsException(amount - balance); } balance -= amount; } }
// Caller code try { account.withdraw(500.0); } catch (InsufficientFundsException e) { System.out.println(e.getMessage()); System.out.println("Need $" + e.getDeficit() + " more"); }

Unchecked Custom Exception

public class NegativePriceException extends RuntimeException { public NegativePriceException(String message) { super(message); } } // Usage: no 'throws' declaration needed public void setPrice(double price) { if (price < 0) { throw new NegativePriceException("Price cannot be negative: " + price); } this.price = price; }

Exception Chaining

When your custom exception is caused by another exception, wrap the original cause so debugging information is preserved throughout the stack trace.

public class DataLoadException extends Exception { public DataLoadException(String msg, Throwable cause) { super(msg, cause); } } // Wrapping an IOException try { readFile(path); } catch (IOException e) { throw new DataLoadException("Failed to load data", e); }

Anatomy of a Custom Exception

CustomException extends Exception FIELDS - errorCode : int - details : String CONSTRUCTORS + CustomException() + CustomException(String message) + CustomException(String msg, Throwable cause) + CustomException(int code, String details) GETTERS + getErrorCode() : int + getDetails() : String

Common Mistakes

✕ Extending Throwable
Never extend Throwable or Error directly. Always extend Exception or RuntimeException.
✕ Forgetting super()
If you don't call super(message) in your constructor, getMessage() will return null.
✕ Swallowing the Cause
When wrapping exceptions, always pass the original as a cause parameter. Lost causes make debugging nearly impossible.

Quick Reference Table

Element What to Do Why
Parent class Exception or RuntimeException Checked vs unchecked behavior
Naming [Problem]Exception Clarity and convention
Constructors No-arg + message + cause Flexibility and chaining
Custom fields Add when caller needs data Programmatic error recovery
super() call Always call in every constructor getMessage() works correctly
serialVersionUID Add for serializable exceptions Avoids InvalidClassException

Question 1 of 5

Which class should you extend to create a checked custom exception?

Question 2 of 5

What happens if a custom exception constructor does not call super(message)?

Question 3 of 5

Is the caller required by the compiler to catch this exception?

Question 4 of 5

Why should you include a Throwable cause parameter in a custom exception constructor?

Question 5 of 5

A method declares throws AlphaException. Which statement is true about a caller of this method?