Custom Exception
Custom exceptions are also called as user defined exceptions
We know that, Java has already provided bunch of exceptions to handle various scenarios like ArithmeticException,NullPointerException,ArrayIndexOutOfBoundException etc.
These exceptions will be thrown by java based on pre-defined conditions
ArithmeticException will be thrown whenever we divide number by zero
NullPointerException will be thrown whenever we access method or variable using NULL reference
ArrayIndexOutOfBoundException will be thrown whenever we access element from array using index out of its limit
We have seen how to throw these exceptions in our previous articles.
Let’s see how to create our own custom exception
We can create custom exception in java by extending Exception or RunTimeException
Example :
MyCustomException.java
- class MyCustomException extends Exception {
- String message;
- MyCustomException(String message) {
- this.message=message;
- }
- public String toString(){
- return ("MyCustomException: "+message) ;
- }
- }
class MyCustomException extends Exception { String message; MyCustomException(String message) { this.message=message; } public String toString(){ return ("MyCustomException: "+message) ; } }
CustomExceptionExample.java
- public class CustomExceptionExample{
- public static void main(String args[]){
- int age=30;
- try{
- System.out.println("Begin: try block");
- // Throwing custom exception based on condition using throw
- if(age > 25){
- throw new MyCustomException("Age can not be greater than 25");
- }
- }
- catch(MyCustomException e){
- System.out.println("Custom exception handler : Catch Block");
- System.out.println(e) ;
- }
- }
- }
public class CustomExceptionExample{ public static void main(String args[]){ int age=30; try{ System.out.println("Begin: try block"); // Throwing custom exception based on condition using throw if(age > 25){ throw new MyCustomException("Age can not be greater than 25"); } } catch(MyCustomException e){ System.out.println("Custom exception handler : Catch Block"); System.out.println(e) ; } } }
In the above example, we have created custom exception by extending Exception class
We have created one parameterized constructor to throw custom exception with message
We have thrown custom exception using throw keyword based on business condition(age >25)
We can also create custom exception by extending RunTimeException class
Example :
InvalidCustomerException.java
- class InvalidCustomerException extends RunTimeException
- {
- public InvalidCustomerException(String s)
- {
- // Call constructor of parent RunTimeException
- super(s);
- }
- }
class InvalidCustomerException extends RunTimeException { public InvalidCustomerException(String s) { // Call constructor of parent RunTimeException super(s); } }
CustomExceptionExample.java
- public class CustomExceptionExample
- {
- void validateCustomer(int customerId) throws InvalidCustomerException {
- if(customerId>10000){
- throw new InvalidCustomerException("Invalid Customer");
- }
- }
- public static void main(String args[])
- {
- CustomExceptionExample obj = new CustomExceptionExample();
- try
- {
- obj.validateCustomer(20000);
- }
- catch (InvalidCustomerException e)
- {
- System.out.println("Catching exception");
- System.out.println(e.getMessage());
- }
- }
- }
public class CustomExceptionExample { void validateCustomer(int customerId) throws InvalidCustomerException { if(customerId>10000){ throw new InvalidCustomerException("Invalid Customer"); } } public static void main(String args[]) { CustomExceptionExample obj = new CustomExceptionExample(); try { obj.validateCustomer(20000); } catch (InvalidCustomerException e) { System.out.println("Catching exception"); System.out.println(e.getMessage()); } } }
In the above example, we have created custom exception by extending RunTimeException
We have thrown RunTimeException in the method based on business condition(customerId >10000)
Note :
Using throws keyword in the method declaration is optional for RunTimeException
When to use custom exception?
We should not simply create custom exceptions unless and until there is a need
We should create custom exceptions only when we need to send some useful information to client
Example, Jackson defines JsonProcessingException which inherits IOException.
If we catch it, we can obtain location information of the parse error using getLocation()
Consider below Example
- public class InvalidNumberException extends Exception
- {
- }
public class InvalidNumberException extends Exception { }
This exception is not giving any useful information to the client code, other than custom exception name
We know that Exception classes are like any other java class where we can add methods that we think client invokes such methods to get more information
Example
- public class InvalidNumberException extends Exception
- {
- private int number;
- public InvalidNumberException (int number){
- this.number=number;
- }
- public int getNumber(){
- return number;
- }
- }
public class InvalidNumberException extends Exception { private int number; public InvalidNumberException (int number){ this.number=number; } public int getNumber(){ return number; } }
In the above example, client can use getNumber() method to get the number which is invalid
Note :
If we need to pass additional information to client then custom exceptions are the best choice