- User defined exception in java
- Example of User defined exception in Java
- Another Example of Custom Exception
- Top Related Articles:
- About the Author
- Comments
- What is User Defined Exception in Java?
- Why Use Custom Exceptions?
- How to Create User-Defined Exceptions in Java?
- 1. Pass the Exception Message to Super Class Constructor and Retrieve It Using the getMesssage() Method
- 2. Override the toString() Method and Customize It with Our Exception Message
- Examples
- 1. Simple User-Defined Exception in Java
- 2.User-Defined Exception for Validating Login Credentials
- 3.User-Defined Exception for Value Less than Threshold Value
- 4. User-defined Exception for Validity of an Entity
- 5.User-defined Exception for Validating the Age of a User
- Learn More
- Conclusion
User defined exception in java
In java we have already defined, exception classes such as ArithmeticException, NullPointerException etc. These exceptions are already set to trigger on pre-defined conditions such as when you divide a number by zero it triggers ArithmeticException, In the last tutorial we learnt how to throw these exceptions explicitly based on your conditions using throw keyword.
In java we can create our own exception class and throw that exception using throw keyword. These exceptions are known as user-defined or custom exceptions. In this tutorial we will see how to create your own custom exception and throw it on a particular condition.
To understand this tutorial you should have the basic knowledge of try-catch block and throw in java.
Example of User defined exception in Java
/* This is my Exception class, I have named it MyException * you can give any name, just remember that it should * extend Exception class */ class MyException extends Exception < String str1; /* Constructor of custom exception class * here I am copying the message that we are passing while * throwing the exception to a string and then displaying * that string along with the message. */ MyException(String str2) < str1=str2; >public String toString() < return ("MyException Occurred: "+str1) ; >> class Example1 < public static void main(String args[])< try< System.out.println("Starting of try block"); // I'm throwing the custom exception using throw throw new MyException("This is My error Message"); >catch(MyException exp) < System.out.println("Catch Block") ; System.out.println(exp) ; >> >
Starting of try block Catch Block MyException Occurred: This is My error Message
Explanation:
You can see that while throwing custom exception I gave a string in parenthesis ( throw new MyException(«This is My error Message»); ). That’s why we have a parameterized constructor (with a String parameter) in my custom exception class.
Notes:
1. User-defined exception must extend Exception class.
2. The exception is thrown using throw keyword.
Another Example of Custom Exception
In this example we are throwing an exception from a method. In this case we should use throws clause in the method signature otherwise you will get compilation error saying that “unhandled exception in method”. To understand how throws clause works, refer this guide: throws keyword in java.
class InvalidProductException extends Exception < public InvalidProductException(String s) < // Call constructor of parent Exception super(s); >> public class Example1 < void productCheck(int weight) throws InvalidProductException< if(weight<100)< throw new InvalidProductException("Product Invalid"); >> public static void main(String args[]) < Example1 obj = new Example1(); try < obj.productCheck(60); >catch (InvalidProductException ex) < System.out.println("Caught the exception"); System.out.println(ex.getMessage()); >> >
Caught the exception Product Invalid
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.
Comments
Hi Sir,
In the first example
public String toString() return (“Output String = “+str1) ;
>
when this block of code is called. I used breakpoint to check when this block is executed. but couldnt really understand what is happening. Please explain this.
Gopinath actually when
System.out.println(exp) ; is executed as we are passing Object type to println() toString() method is called, here they have overrided the toString() so we get the output: Output String = Custom Hope this helps
ya we can do it. if you want to write user define exception you need to catch that exception and your class should extends from RuntimeException and you need to write cause for exception
What is User Defined Exception in Java?
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?
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.
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 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.
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 the 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.
Conclusion
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.