- What are Custom Exceptions in Java?
- Why Use Custom Exceptions?
- Example 1: How to Create a Custom Checked Exception
- Scenario: File Compression Tool
- Step-by-Step Implementation:
- Example 2: How to Create a Custom Unchecked Exception
- Scenario: Online Shopping Cart
- Step-by-Step Implementation:
- Checked vs Unchecked Custom Exceptions
- Best Practices for Custom Exceptions
- Summary: Key Takeaways
- Final Words for Students
- Practice Questions for You
Imagine you’re creating a school management system. You already know that Java provides built-in exceptions like NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException, etc. But what if you want to create your own specific exception like:
StudentNotFoundExceptionInvalidMarkExceptionCourseFullException
These exceptions don’t exist in Java by default, so we need a way to create them.
👉 That’s where Custom Exceptions come into play.
What are Custom Exceptions in Java?
Custom Exceptions are user-defined exceptions created by extending the Exception or RuntimeException class.
They allow us to define meaningful exception types tailored to our application’s needs, which makes our error handling more readable and maintainable.
Why Use Custom Exceptions?
Let’s understand why we need them:
| Reason | Explanation |
|---|---|
| 📌 Improve Code Readability | Custom names like InsufficientBalanceException clearly tell what’s wrong. |
| 📌 Focused Error Handling | You can catch and handle specific business logic errors. |
| 📌 Reusability | Reuse custom exceptions in multiple places. |
| 📌 Clean Code Architecture | Keeps business logic separate from error-handling logic. |
Example 1: How to Create a Custom Checked Exception
Scenario: File Compression Tool
We’re building a file compression tool. If a user tries to compress a file larger than 1 GB, we want to throw a custom checked exception called FileTooLargeException.
Step-by-Step Implementation:
- Create the custom checked exception.
- Use it in your business logic.
- Handle it using try-catch.
Class : FileTooLargeException.java
// Custom checked exception for large files
public class FileTooLargeException extends Exception {
public FileTooLargeException(String message) {
super(message);
}
}
Class : FileCompressor.java
public class FileCompressor {
private static final int MAX_FILE_SIZE_MB = 1024;
public void compressFile(int fileSizeInMB) throws FileTooLargeException {
if (fileSizeInMB > MAX_FILE_SIZE_MB) {
throw new FileTooLargeException("File size exceeds the maximum limit of 1024 MB. Size provided: " + fileSizeInMB + " MB");
}
System.out.println("File compressed successfully!");
}
public static void main(String[] args) {
FileCompressor compressor = new FileCompressor();
try {
compressor.compressFile(1500); // Too large
} catch (FileTooLargeException e) {
System.out.println("Compression failed: " + e.getMessage());
}
}
}
🧾 Output:
Compression failed: File size exceeds the maximum limit of 1024 MB. Size provided: 1500 MB
📌 Notes:
- Because this is a checked exception (extends Exception), we must declare it using throws and handle it using try-catch.
- It enforces compile-time checking, which is helpful in reliable system design.
Example 2: How to Create a Custom Unchecked Exception
Scenario: Online Shopping Cart
You’re building an online shopping cart system. If a user tries to add a negative quantity of an item, we’ll throw a custom unchecked exception called InvalidQuantityException.
Step-by-Step Implementation:
- Create the custom unchecked exception.
- Throw it without needing to declare or catch it explicitly.
Class: InvalidQuantityException.java
// Custom unchecked exception for invalid quantity
public class InvalidQuantityException extends RuntimeException {
public InvalidQuantityException(String message) {
super(message);
}
}
Class: ShoppingCart.java
public class ShoppingCart {
public void addItemToCart(String itemName, int quantity) {
if (quantity <= 0) {
throw new InvalidQuantityException("Quantity must be greater than zero. Provided: " + quantity);
}
System.out.println(quantity + " x " + itemName + " added to cart.");
}
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
cart.addItemToCart("Wireless Mouse", 2); // Valid
cart.addItemToCart("USB Cable", -3); // Invalid - will throw unchecked exception
}
}
Output
2 x Wireless Mouse added to cart.
Exception in thread "main" InvalidQuantityException: Quantity must be greater than zero. Provided: -3
📌 Notes:
- Since it extends RuntimeException, this exception is unchecked.
- You are not forced to catch it, making it ideal for input validation or programming logic errors.
Checked vs Unchecked Custom Exceptions
| Feature | Checked Exception | Unchecked Exception |
|---|---|---|
| Base Class | Exception | RuntimeException |
| Compile-Time Check | Yes | No |
| Needs Try-Catch? | Yes (or must be declared) | No (optional) |
| Example | InvalidAgeException | NegativeAmountException |
Best Practices for Custom Exceptions
public class DetailedException extends Exception {
private int errorCode;
public DetailedException(String message, int errorCode) {
super(message);
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
}
Summary: Key Takeaways
| Concept | Explanation |
|---|---|
| What is it? | A way to define your own exception types. |
| Why needed? | To handle business logic errors more clearly. |
| How to create? | Extend Exception (checked) or RuntimeException (unchecked). |
| Example? | InvalidAgeException, CourseFullException |
| Best use? | For domain-specific error handling like banking, education, healthcare apps. |
Final Words for Students
- Custom exceptions are not just a Java feature—they’re a software design strategy.
- Whenever you feel “this kind of error needs special attention”, go ahead and create a custom exception.
- Don’t overuse them. Only use them where built-in exceptions don’t express the real problem clearly.
Practice Questions for You
- Create a custom exception
LowBalanceExceptionand use it in a bank withdrawal scenario. - Create
InvalidEmailExceptionand validate email input from the user. - Implement
FileSizeLimitExceededExceptionin a file upload app simulation.