Custom Exceptions
in Java
Learn how to design and implement your own exception classes to create more meaningful, descriptive error handling in Java applications.
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
Why Create Custom Exceptions?
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
Extending Exception vs RuntimeException
How to Create a Custom Exception
Example 1: InvalidAgeException
Example 2: Adding Custom Fields
Example 3: Using It in Practice
Unchecked Custom Exception
Exception Chaining
When your custom exception is caused by another exception, wrap the original cause so debugging information is preserved throughout the stack trace.
Anatomy of a Custom Exception
Common Mistakes
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
Consider the following code:
public class TooManyItemsException extends RuntimeException {
private final int count;
public TooManyItemsException(int count) {
super("Too many items: " + count);
this.count = count;
}
public int getCount() { return count; }
}
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
Consider these two exception classes:
Class A:
public class AlphaException extends Exception {
public AlphaException(String msg) { super(msg); }
}
Class B:
public class BetaException extends RuntimeException {
public BetaException(String msg) { super(msg); }
}
A method declares throws AlphaException. Which statement is true about a caller of this method?