Home » Java » Custom Exception in Java

Custom Exception in Java

Introduction :

Sometimes it is required to develop meaningful exceptions based on application requirements.For example suppose you have one savings account in any Bank and you have 50 dollars in your account.Suppose you attempted to withdraw 60 dollars from your account. In java you can handle this scenario by using ArithmeticException.But this Exception is not meaningful as a user point of view. You need to display some error message related to insufficient fund.

To have good meaning, we can create our own exception. If an exception like InSufficientFundException exists, it well suits for the problem of insufficient funds.

They help application clients to better understand what went wrong. They are particularly useful for doing exception handling for REST APIs as different business logic constraints require different response codes to be sent back to the client.

Custom Checked Exception

Let's consider a scenario where we want to validate a phone number that is passed as an argument to a method. Our first requirement is to check whether phone no is valid or not. Now we could use Java's built-in IllegalArgumentException, which is fine if we are just checking for a single thing like whether it matches a predefined format of a phone number.

Now suppose we also have a business condition to check that all phones in our system need to be unique. Now we have to perform a second check (DB/network call). We can, of course, use the same IllegalArgumentException, but it will be not clear what the exact cause is - whether the phone failed phone validation or the phone already exists in the database.

  • The user defined exception class must extend from java.lang.Exception or java.lang.RunTimeException class. Also note that RuntimeException and its sub classes are not checked by the compiler and need not be declared in the method's signature.
  • While creating custom exception, prefer to create an unchecked, Runtime exception than a checked exception.
  • Apart from providing default no argument constructor on your custom Exception class, consider providing at least two more constructors, one which should accept a failure message and other which can accept another Throwable as cause.
  • Every user defined exception class parametrized Constructor must called parametrized Constructor of either java.lang.Exception or java.lang.RunTimeException class by using super(string parameter always).

Here is complete example of how to create a user defined custom Exception in Java.

In this example 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 exceed your bank balance? You will not be allowed, and this is where user defined exception comes into picture. We have created a custom exception called InSufficientFundException to handle this scenario.

InSufficientFundException.java

This is Custom Exception class.In this class we have created two constructors for displaying error message.


package com.jwt.core.java;

public class InSufficientFundException extends RuntimeException {

	private String message;

	public InSufficientFundException(String message) {
		this.message = message;
	}

	public InSufficientFundException(Throwable cause, String message) {
		super(cause);
		this.message = message;
	}

	public String getMessage() {
		return message;
	}

}

Account.java

In this class we have created two methods withdraw and deposit.Initial Balance of Account is 3000 dollars.Withdraw method parameter is amount and that amount we are subtracting from initial balance. If amount passes is greater than initial balance, it will throw Custom Exception InSufficientFundException,else it will calculate new balance by subtracting amount from initial balance.


package com.jwt.core.java;

public class Account {

	private int balance = 3000;

	public int balance() {
		return balance;
	}

	public void withdraw(int amount) throws InSufficientFundException {
		if (amount > balance) {
			throw new InSufficientFundException(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));
		}
	}

}

Test.java

Now create a test class to test our implemented Custom Exception Class.


package com.jwt.core.java;

public class Test {

	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(3500);

	}

}

Output

Current balance : 2800
Exception in thread "main" com.jwt.core.java.InSufficientFundException: Current balance 2800 is less than requested amount 3500
	at com.jwt.core.java.Account.withdraw(Account.java:13)
	at com.jwt.core.java.Test.main(Test.java:11)

Previous Next Article

comments powered by Disqus