What is User Defined Exception in Java?

An exception is a case where the normal flow of the program execution is disrupted.
Java provides a few built-in exceptions, which are again segregated as compile-time and runtime exceptions. We are in a sunny day scenario until our use case is satisfied with one of the built-in exceptions, but what if there's no such exception that fits our use case, or do we want to customize the exception? When creating custom exceptions in Java, there are certain rules to follow to ensure proper exception handling.
User-defined exceptions are also referred to as custom exceptions. The exceptions created per our use case and thrown using the throw keyword are user-defined exceptions, and such exceptions are derived classes of the Exception class from the java.lang package.
Introduction to Exceptions
Exceptions in Java are special events that interrupt the normal flow of a program’s execution. These events can be triggered by a variety of factors, such as invalid user input, issues with network connections, or unexpected programming errors. To manage these disruptions, Java provides a comprehensive exception handling mechanism that allows developers to write code capable of responding to errors gracefully.
At the core of this mechanism is the exception class hierarchy. In Java, all exceptions are represented as objects that are instances of classes extending the base Exception class. This design enables developers to create their own custom exception classes, tailored to represent application specific errors that may arise during program execution. By defining a custom exception, you can provide more meaningful error messages and handle errors in a way that is specific to your application’s needs.
Writing robust Java code involves anticipating potential errors and using exceptions in java to manage them effectively. Whether you are handling built-in exceptions or creating a custom exception class, understanding how exceptions work is essential for building reliable and maintainable applications.
Types of Exceptions
Java categorizes exceptions into two main types: checked exceptions and unchecked exceptions. Understanding the difference between these types is crucial for effective exception handling in your code.
Checked exceptions
Checked exceptions are those that inherit from the Exception class (excluding RuntimeException and its subclasses). These exceptions typically represent conditions that a well-written application should anticipate and recover from, such as file not found errors or issues with network connectivity. When a method can throw a checked exception, it must either handle the exception using a try-catch block or declare it in its method signature with the throws clause. This requirement ensures that checked exceptions are explicitly acknowledged and managed during program execution.
Unchecked exceptions
Unchecked exceptions, on the other hand, are subclasses of the RuntimeException class. These exceptions usually indicate programming errors, such as accessing an array out of bounds or dereferencing a null object. Unchecked exceptions do not need to be declared in a method signature or explicitly caught in a catch block, as they often represent bugs that should be fixed in the code rather than handled at runtime.
When creating your own custom exception, you can choose to make it a checked or unchecked exception by extending either the Exception class or the RuntimeException class, respectively. This flexibility allows you to design exception handling strategies that best fit your application’s requirements.
Why Use Custom Exceptions?
Although java provides the Exception class, which covers almost all cases of exceptions that could be raised during program execution, custom exceptions will bring the spotlight onto exception handling.
Custom exceptions enable the flexibility of adding messages and methods that are not part of the Exception class. They can be used to store case-specific messages like status codes and error codes or override an existing method to present the exception as per the use case. Custom exceptions enable the flexibility of adding messages and methods that are not part of the Exception class. They can be used to store case-specific messages like status codes and error codes or override an existing method to present the exception as per the use case.
Custom exceptions are helpful while writing exceptions for business logic. It helps the application developers to better understand the exception, which is business-specific.
Now that we are aware of custom exceptions in java and their use cases, let's have a look at how to create them.
How to Create User-Defined Exceptions in Java?
To create a custom exception in java, we have to create a class by extending it with an Exception class from the java.lang package.
It's always a good practice to add comments and follow naming conventions to easily identify and recognize the benefit of our exception class.
Below is the template to be followed for creating a user-defined exception in java. You can define constructors with different args (parameters) to pass custom data to your exception. For example, you might declare your custom exception as public InsufficientFundsException(String message) to accept a custom message. When a method might throw your custom exception, you should use the throws InsufficientFundsException clause in the method signature. To create and throw your exception, you can use throw new MyException("Custom error message").
Let's add our custom message to the exception class. This can be done in two ways :
1. Pass the Exception Message to Super Class Constructor and Retrieve It Using the getMesssage() Method
Here's the code to demonstrate that in java
In the above code, we've made a call to the parent class constructor using the super keyword. Since the custom class is extended by the Exception class, it is considered to be the parent class, and the Exception class has a parameter constructor which expects a string. It will construct a new exception with the specified message that can be retrieved later using the getMessage() method.
Learn more about this and super keyword in Java from this informative article over here.
2. Override the toString() Method and Customize It with Our Exception Message
Here's the code to demonstrate that in Java
In the above code, we've overridden the toString() method. Usually, when we print an object of a java class, it prints the hashcode of that object (default implementation of the toString() method). Overriding the toString() method provides the flexibility to customize the print statement when we print an object. Now that we've overridden the method with our custom message, the user only needs to print the exception object to know the exception message. Easy, right?
Now that we've seen how to create a user-defined exception class in Java, let's see how to use our custom exception and have a walkthrough over a few more examples.
Examples
1. Simple User-Defined Exception in Java
In order to use our custom exception, we've to create a new object of the class and throw it using the throw keyword.
Here's the code to demonstrate that in Java
Note that the throw keyword has to be inside a try block, and the corresponding exception is caught in a catch block.
Call to the super constructor has to be the first statement inside a constructor.
2.User-Defined Exception for Validating Login Credentials
Consider a use case where we want to validate the login credentials entered by the user and throw an exception with a specific error message or a specific status code to make the user better understand the exception. We can define a custom exception for this case. Let's have a look over it.
In the above Java program, we've defined a custom exception, InvalidCredentialsException and added our specific error message. In the main method, we've updated the id and password variables with user input. We've put a conditional check to validate the credentials inside a try block, which throws an InvalidCredentialsException if the credentials are not valid. Then we've written a catch block to print our custom exception message.
3.User-Defined Exception for Value Less than Threshold Value
Consider a use case where a value has to be entered by a user or returned by another process, and the value has to be greater than a threshold value; else, we've raised an exception. This exception matches the example case where a user is trying to withdraw some amount, and the amount cannot be negative or zero. Let's have a look over the custom exception for this case in Java.
In the above java program, we've defined a custom exception, AmountLessThanRequiredException, and added our specific error message. In the main method, we've updated the withdrawAmount variable with user input. We've put a condition to check if the given withdrawal amount is less than or equal to zero inside a try block, which throws an AmountLessThanRequiredException if credentials are not valid. Then we've written a catch block to print our custom exception message.
4. User-defined Exception for Validity of an Entity
Consider a use case where a user is trying to access or log in with expired entity details, for example, a user trying to log in to an application where the provided credentials are no more active. In such a case, a user-defined exception with a custom message helps the user better understand the exception.
Here's the code to do that in Java.
In the above java program, we've defined a custom exception, IdDoesnotExistException, and added our specific error message. In the main method, we've updated the id variable with user input. Let's imagine that there's a function named getIdList() which returns a set of all active IDs. We've put an if condition to check if the given id is active inside a try block, which throws an IdDoesnotExistException if the id is not active or invalid. Then we've written a catch block to print our custom exception message.
5.User-defined Exception for Validating the Age of a User
Consider a use case where the user has to input an integer, and the value must be greater than or fit in a range, else we've to raise an exception. This exception matches the example case where the user tries to register for voter ID, which has an age restriction of 18. Let's create a custom exception for this case with a custom message describing the exception.
Let's have a look over the code!
In the above java program, we've defined a custom exception, AgeDoesNotFitException, and added our specific error message. In the main() method, we've updated the age variable with user input. We've put a conditional check to compare the given age with the required age limit inside a try block, which throws an AgeDoesNotFitException if credentials are not valid. Then we've written a catch block to print our custom exception message.
Learn More
Now that we’ve explored the definition of user-defined examples and walked through a few examples and use cases, you might have built up some interest in the concept of exception handling in Java (of course, it is an interesting topic). Fasten your enthusiasm by reading this interesting blog on exception handling over here.
Explore Scaler Topics Java Tutorial and enhance your Java skills with Reading Tracks and Challenges.
Conclusion
In summary, Java custom exceptions are a vital feature for building robust and maintainable applications. By creating your own exception class that extends the Exception class or one of its subclasses, you can represent application specific errors with clarity and precision. Java custom exceptions allow you to provide detailed error messages and implement error handling that is tailored to your program’s unique needs.
Understanding the distinction between checked and unchecked exceptions in java is key to writing effective error handling code. Custom exceptions can be designed as either type, depending on whether you want to enforce handling at compile time or signal programming errors at runtime. By leveraging custom exception classes, you can improve the quality of your code, make debugging easier, and ensure that your application responds gracefully to unexpected situations.
With practice, you’ll become adept at using java custom exceptions to create reliable and user-friendly software. Remember, thoughtful error handling is a hallmark of professional Java development. Happy coding!
Let's recall
- An exception breaks the normal execution flow.
- User-defined exceptions provide the flexibility to customize the exception as per our use case.
- A custom exception class must extend the Exception class from the java.lang package.
- Error message of a custom exception can be configured by passing a message to the super class constructor or by overriding the toString() method.
- To use our custom exception, we've to create a new object of the custom exception class and throw it using the throw keyword.