🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Creating a custom exception in Java is a straightforward process. In this guide, we will see step-by-step how to create custom exceptions in Java.
Steps to Create a Custom Exception in Java
1. Decide the Exception Type:
Decide whether your exception should be checked or unchecked.
Checked Exceptions: These are the exceptions that a method can throw but cannot handle on its own. Any method that might throw a checked exception must either handle it using a try-catch block or declare it using the throws keyword.
Unchecked Exceptions: These are the exceptions that can be thrown during the execution of the program but were not anticipated. They extend RuntimeException and don't need to be declared or caught.
2. Choose a Meaningful Name:
Your custom exception name should typically end with "Exception" to maintain clarity and adhere to Java's naming convention.
For example:
ResourceNotFoundException
BadRequestException
AgeValidatorException
BlogAPIException
3. Extend the Appropriate Exception Class:
For checked exceptions, extend the Exception class.
For unchecked exceptions, extend the RuntimeException class.
4. Create Constructors:
To give more context or customization ability to your exception, create constructors for it. At a minimum, you should provide:
- A default constructor.
- A constructor that takes a string parameter for the error message.
- Additional constructors as required (e.g., to initialize custom fields).
5. (Optional) Add Custom Fields and Methods:
If you want your exception to hold additional information or provide specific functionalities, you can add custom fields and methods.
Now, let's see how to use the above step to create custom-checked exceptions and custom-unchecked exceptions.
Create a Checked Custom Exception
Let's create a checked custom exception named InvalidOrderException:
public class InvalidOrderException extends Exception {
public InvalidOrderException() {
super("The order is invalid");
}
public InvalidOrderException(String message) {
super(message);
}
}Create a Custom Unchecked Exception
public class OrderConfigurationException extends RuntimeException {
public OrderConfigurationException() {
super("Configuration of the order is incorrect");
}
public OrderConfigurationException(String message) {
super(message);
}
}Using Custom Exceptions
You can throw your custom exception just like any other exception using the throw statement.
public class OrderProcessor {
public void validateOrder(Order order) throws InvalidOrderException {
if(order == null || order.getItems().isEmpty()) {
throw new InvalidOrderException("Order is empty or null");
}
}
public void configureOrder(Order order) {
if(order.getConfiguration() == null) {
throw new OrderConfigurationException("Order lacks necessary configuration");
}
}
}Usage
For the checked exception (InvalidOrderException), you'll either need to catch it or declare that your method may throw it:
public static void main(String[] args) {
OrderProcessor processor = new OrderProcessor();
try {
processor.validateOrder(null); // This will throw InvalidOrderException
} catch (InvalidOrderException e) {
System.out.println("Error: " + e.getMessage());
}
processor.configureOrder(new Order()); // This will throw OrderConfigurationException
}Best Practices to Create Custom Exceptions in Java
- For checked exceptions, extend the Exception class.
- For unchecked exceptions, extend the RuntimeException class.
public class CustomException extends Exception {
public CustomException() { super(); }
public CustomException(String message) { super(message); }
public CustomException(String message, Throwable cause) { super(message, cause); }
public CustomException(Throwable cause) { super(cause); }
}My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment