Java's built-in exceptions (like IllegalArgumentException and IOException) are generic. In a real production application, you need exceptions that carry domain-specific meaning. When a user attempts to withdraw more money than their balance, throwing a generic RuntimeException is unhelpful. Throwing a InsufficientFundsException immediately communicates the exact business rule that was violated.
Custom Exceptions are created by extending either Exception (to create a Checked Exception that callers must handle) or RuntimeException (to create an Unchecked Exception). The best practice is to accept a message string and a cause Throwable in the constructors, forwarding both to the parent using super(). This ensures your custom exception integrates seamlessly with Java's standard exception chaining and logging infrastructure.
Well-designed custom exception hierarchies make a codebase dramatically easier to maintain. Instead of checking error codes in returned strings, callers can catch specific exception types and respond accordingly.
// 1. Define the Custom Exception
// Extends RuntimeException → Unchecked, no 'throws' declaration needed
public class InsufficientFundsException extends RuntimeException {
private double shortfall; // Domain-specific data!
public InsufficientFundsException(double shortfall) {
super("Insufficient funds. You need $" + shortfall + " more.");
this.shortfall = shortfall;
}
// Custom getter for structured error responses
public double getShortfall() {
return shortfall;
}
}
// 2. Use the Custom Exception in Business Logic
public class BankAccount {
private double balance = 100.00;
public void withdraw(double amount) {
if (amount > balance) {
throw new InsufficientFundsException(amount - balance);
}
balance -= amount;
}
}
// 3. Catch the Specific Business Exception
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
try {
acc.withdraw(250.00);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
System.out.println("You are short: $" + e.getShortfall());
}
}
}super(message, cause) in the constructor. If you create a custom exception but pass nothing to super, the parent's message and cause chain are lost, making e.getMessage() return null and log files completely useless.UserEmailInvalidException, UserPasswordTooShortException, and UserAgeUnderMinimumException as three completely separate classes adds enormous boilerplate. Group related validations under one UserValidationException that carries a specific error code field instead.Exception (Checked), every method in your codebase that calls anything throwing your exception must declare throws YourException. This cascades through the entire call stack. Extend RuntimeException unless you have a very explicit reason to force compile-time handling.When should you extend Exception vs RuntimeException for a Custom Exception?
Extend Exception (Checked) when the failure is a foreseeable, recoverable business condition that the caller should always explicitly handle — like InsufficientFundsException. Extend RuntimeException (Unchecked) for programming errors or violations of contracts that represent bugs, not expected conditions — like InvalidConfigurationException.
Why is it best practice to add a cause parameter to your custom exception's constructor?
To support Exception Chaining. When you catch a lower-level exception (like SQLException) and throw your own custom one, passing the original as the cause (super(message, cause)) preserves the full diagnostic chain. Without it, the original root cause is permanently hidden from logs and stack traces, making debugging exponentially harder.
Spring Boot APIs use custom exceptions combined with @ControllerAdvice (a global exception handler) to automatically translate business exceptions into clean HTTP error responses, without any repetitive try-catch code in each controller.
// Custom Exception
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String id) {
super("Resource not found: " + id);
}
}
// Spring automatically catches this and returns HTTP 404
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleNotFound(ResourceNotFoundException e) {
return ResponseEntity.status(404).body(e.getMessage());
}
}Test your understanding of Custom Exceptions with these quick questions.
Question 1
Which base class should a Custom Checked Exception extend?
Question 2
What is the main advantage of creating a custom exception with a specific field (like `double shortfall`)?
Question 3
Why should you always provide `super(message, cause)` in a custom exception constructor?
Java's built-in exceptions (like IllegalArgumentException and IOException) are generic. In a real production application, you need exceptions that carry domain-specific meaning. When a user attempts to withdraw more money than their balance, throwing a generic RuntimeException is unhelpful. Throwing a InsufficientFundsException immediately communicates the exact business rule that was violated.
Custom Exceptions are created by extending either Exception (to create a Checked Exception that callers must handle) or RuntimeException (to create an Unchecked Exception). The best practice is to accept a message string and a cause Throwable in the constructors, forwarding both to the parent using super(). This ensures your custom exception integrates seamlessly with Java's standard exception chaining and logging infrastructure.
Well-designed custom exception hierarchies make a codebase dramatically easier to maintain. Instead of checking error codes in returned strings, callers can catch specific exception types and respond accordingly.
// 1. Define the Custom Exception
// Extends RuntimeException → Unchecked, no 'throws' declaration needed
public class InsufficientFundsException extends RuntimeException {
private double shortfall; // Domain-specific data!
public InsufficientFundsException(double shortfall) {
super("Insufficient funds. You need $" + shortfall + " more.");
this.shortfall = shortfall;
}
// Custom getter for structured error responses
public double getShortfall() {
return shortfall;
}
}
// 2. Use the Custom Exception in Business Logic
public class BankAccount {
private double balance = 100.00;
public void withdraw(double amount) {
if (amount > balance) {
throw new InsufficientFundsException(amount - balance);
}
balance -= amount;
}
}
// 3. Catch the Specific Business Exception
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
try {
acc.withdraw(250.00);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
System.out.println("You are short: $" + e.getShortfall());
}
}
}super(message, cause) in the constructor. If you create a custom exception but pass nothing to super, the parent's message and cause chain are lost, making e.getMessage() return null and log files completely useless.UserEmailInvalidException, UserPasswordTooShortException, and UserAgeUnderMinimumException as three completely separate classes adds enormous boilerplate. Group related validations under one UserValidationException that carries a specific error code field instead.Exception (Checked), every method in your codebase that calls anything throwing your exception must declare throws YourException. This cascades through the entire call stack. Extend RuntimeException unless you have a very explicit reason to force compile-time handling.When should you extend Exception vs RuntimeException for a Custom Exception?
Extend Exception (Checked) when the failure is a foreseeable, recoverable business condition that the caller should always explicitly handle — like InsufficientFundsException. Extend RuntimeException (Unchecked) for programming errors or violations of contracts that represent bugs, not expected conditions — like InvalidConfigurationException.
Why is it best practice to add a cause parameter to your custom exception's constructor?
To support Exception Chaining. When you catch a lower-level exception (like SQLException) and throw your own custom one, passing the original as the cause (super(message, cause)) preserves the full diagnostic chain. Without it, the original root cause is permanently hidden from logs and stack traces, making debugging exponentially harder.
Spring Boot APIs use custom exceptions combined with @ControllerAdvice (a global exception handler) to automatically translate business exceptions into clean HTTP error responses, without any repetitive try-catch code in each controller.
// Custom Exception
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String id) {
super("Resource not found: " + id);
}
}
// Spring automatically catches this and returns HTTP 404
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleNotFound(ResourceNotFoundException e) {
return ResponseEntity.status(404).body(e.getMessage());
}
}Test your understanding of Custom Exceptions with these quick questions.
Question 1
Which base class should a Custom Checked Exception extend?
Question 2
What is the main advantage of creating a custom exception with a specific field (like `double shortfall`)?
Question 3
Why should you always provide `super(message, cause)` in a custom exception constructor?