1. Introduction
While Java's built-in exceptions (like IllegalArgumentException or IOException) cover many common cases, real applications often have domain-specific error conditions — such as InsufficientFundsException in a banking app — that are better represented by custom exception classes.
Cricket analogy: Standard umpiring signals like 'wide' or 'no-ball' cover common infractions, but a domain-specific rule violation like a bowler's suspicious action needs a specialized report to the match referee, just as InsufficientFundsException handles a domain-specific banking error.
A custom exception is simply a class that extends Exception (making it checked) or RuntimeException (making it unchecked), giving it a clear, self-documenting name and the ability to carry extra context about the failure.
Cricket analogy: A specialized 'BallTamperingViolation' report, filed by extending the standard misconduct report format, gives officials a clearly named, context-rich record rather than a vague foul, just as a custom exception extends Exception or RuntimeException to add clarity.
2. Syntax
// Checked custom exception
public class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
// Unchecked custom exception
public class InvalidAgeException extends RuntimeException {
public InvalidAgeException(String message) {
super(message);
}
}
// Throwing a custom exception
throw new InsufficientFundsException("Balance too low for withdrawal");3. Explanation
To create a custom exception, extend either Exception or RuntimeException depending on whether you want callers to be forced to handle it (checked) or not (unchecked). By convention, custom exception classes provide constructors mirroring their parent — typically a no-arg constructor, a String message constructor, and a String message plus Throwable cause constructor — so the exception integrates well with existing exception-handling code and preserves the original cause chain.
Cricket analogy: Choosing to file a mandatory disciplinary report that every match referee must formally address, versus an optional advisory note officials can ignore, mirrors choosing checked Exception versus unchecked RuntimeException; and providing three report formats—blank, with-a-reason, and with-a-reason-plus-video-evidence—mirrors the standard constructor set.
The throw keyword is used to actually raise an instance of the exception (throw new MyException(...)), while the throws keyword appears in a method's signature to declare that the method may propagate a checked exception to its caller, without handling it itself.
Cricket analogy: An umpire actively raising his finger to give a batsman out is like the throw keyword actually triggering the dismissal, while the match rulebook's clause stating 'a bowler's action may be reported for review' without resolving it itself is like throws, declaring the possibility without handling it.
Exam trap: throw (no 's') is a statement used inside a method body to raise an exception instance. throws (with 's') is a clause in the method signature declaring which checked exceptions the method might propagate. Mixing these up is a very common exam question.
4. Example
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
public class CustomExceptionDemo {
static void withdraw(double balance, double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Cannot withdraw " + amount + ", balance is " + balance);
}
System.out.println("Withdrawal of " + amount + " successful.");
}
public static void main(String[] args) {
try {
withdraw(100.0, 150.0);
} catch (InsufficientFundsException e) {
System.out.println("Transaction failed: " + e.getMessage());
}
}
}5. Output
Transaction failed: Cannot withdraw 150.0, balance is 100.06. Key Takeaways
- A custom exception is a class extending Exception (checked) or RuntimeException (unchecked).
- Custom exception classes typically provide constructors matching the parent, especially the String message constructor.
- throw raises an exception instance; throws declares in a method signature that a checked exception may propagate.
- Custom exceptions give clearer, more domain-specific error names than generic built-in exceptions.
- Methods declaring a checked custom exception with throws force callers to catch or re-declare it.
Practice what you learned
1. To make a custom exception checked, which class should it extend?
2. What is the difference between throw and throws?
3. Which constructor is most commonly provided in a custom exception class?
4. If a custom exception extends RuntimeException, is it checked or unchecked?
5. What must a method do if it might throw a checked custom exception without catching it?
Was this page helpful?
You May Also Like
Exceptions in Java
Understand what exceptions are in Java, how the Throwable hierarchy is organized, and why exception handling keeps programs robust.
try-catch in Java
Learn how to use try, catch, multi-catch, and try-with-resources blocks in Java to handle exceptions cleanly.
Checked vs Unchecked Exceptions in Java
Compare checked and unchecked exceptions in Java, including compiler enforcement, typical use cases, and common exam pitfalls.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics