How to create User Defined Exception class in Java? Example Tutorial

Java has very good support for handling Errors and Exceptions, It has a well-defined Exception hierarchy and language level support to throw and catch Exceptions and deal with them. Java Programmers often deal with built-in exceptions from java.lang package and several others which are already defined in JDK API like 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, like 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 your 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 exceptions 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 conditions differently. It's one of the simplest examples to understand the need for customized exceptions 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 that 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 users and programmers.

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)

In this code example, I have defined a custom exception class in Java named NotSufficientFundException. This class extends the RuntimeException class, making it an unchecked exception. Unchecked exceptions do not need to be explicitly declared in the method signature or handled using a try-catch block, providing flexibility in their usage.

In this example, if the withdraw method is called with an amount greater than the current balance, it throws a NotSufficientFundException with a specific error message indicating the insufficiency of funds

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 the error. 

A little bit difficult part is choosing between checked and unchecked exceptions 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

Feel free to comment, ask questions if you have any doubt.