How to create User Defined Exception class in Java

Java has the very good support of handling Error and Exception, It has a well-defined Exception hierarchy and language level support to throw and catch Exception and deal with them. Java Programmers often deals with built-in exceptions from java.lang package and several others which are already defined in JDK API e.g. NullPointerException. If you have read Effective Java, you may remember the advice of Joshua Bloch regarding Exception. According to him, you should try to reuse the Exception classes provided in the JDK, e.g., IndexOutOfBoundException, ArithmeticException, IOException, and java.lang.ArrayIndexOutOfBoundsException , instead of creating new ones for a similar purpose. But there are cases when a user-defined, the custom exception provides a better opportunity to deal with special cases.

So remember, you can always create you own Exception classes by extending from the class Exception or one of its subclasses. Also note that RuntimeException and its subclasses are not checked by the compiler and need not be declared in the method's signature.

Therefore, use them with care, as you will not be informed and may not be aware of the exceptions that may occur by using that method (and therefore do not have the proper exception handling codes) – a bad software engineering practice. Once again, even Joshua Bloch has advised using standard exception in Effective Java.





User Defined Exception in Java

Here is a complete example of how to create a user-defined custom Exception in Java. By using this you can handle different error condition differently. It's one of the simplest examples to understand the need of customized exception in Java. Here we have an Account class, which is representing a bank account where you can deposit and withdraw money, but what will happen if you want to withdraw money which exceeds your bank balance? You will not be allowed, and this is where user defined exception comes into the picture. We have created a custom exception called NotSufficientFundException to handle this scenario. This will help you to show a more meaningful message to user and programmer.

How to create User Defined Exception in Java
/**
* Java Program to create your own Exception class and use it.
*
* @author Javin Paul
*/
public class UserDefinedException {
 
    public static void main(String args[]) {
        Account acct = new Account();
        System.out.println("Current balance : " + acct.balance());
        System.out.println("Withdrawing $200");
        acct.withdraw(200);
        System.out.println("Current balance : " + acct.balance());
        acct.withdraw(1000);
 
    }
 
}

/**
  * Java class to represent a Bank account which holds your balance and provide wi
  */  
public class Account {
 
    private int balance = 1000;
 
    public int balance() {
        return balance;
    }
 
    public void withdraw(int amount) throws NotSufficientFundException {
        if (amount > balance) {
            throw new NotSufficientFundException(String.format("Current balance %d is less than requested amount %d", balance, amount));
        }
        balance = balance - amount;
    }
 
    public void deposit(int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException(String.format("Invalid deposit amount %s", amount));
        }
    }
 
}


/**
   * User defined Exception class in Java
   */ 
public class NotSufficientFundException extends RuntimeException {
 
    private String message;
 
    public NotSufficientFundException(String message) {
        this.message = message;
    }
 
    public NotSufficientFundException(Throwable cause, String message) {
        super(cause);
        this.message = message;
    }
 
    public String getMessage() {
        return message;
    }

}
 
Output
Current balance : 1000
Withdrawing $200
Current balance : 800
Exception in thread "main" NotSufficientFundException: Current balance 800 is less than requested amount 1000
               at Account.withdraw(Testing.java:68)
               at Testing.main(Testing.java:51)


That's all about how to create a user-defined exception in Java. You can see here use of NotSufficientFundException not only help you to show a more meaningful message to the user but also helps in debugging and logging. If you look at this exception in the log file you will immediately find the cause of error. Little bit difficult part is choosing between checked and unchecked exception to create a custom Exception. You should by default use RuntimeException to make your user define exception unchecked mainly to avoid clutter, but if you want to ensure that client must handle that exception then make sure to inherit from Exception to create a user defined checked exception.

1 comment:

  1. What Is the point of using 'NotSufficientFundException' In the method signature If It Is extending RE?

    ReplyDelete