User defined exception in java

User defined exception in java can be created by extending any predefined exception. User defined exception in java are also called Custom Exceptions. In java if we are developing an application and get some requirement to instruct the user who is going to use our class about the problem occurred while executing the statement.

To define user defined exception in java we can follow the below steps:-

  • Define a java class by extending any predefined exception but it is recommended to extend either java.lang.Exception or java.lang.RuntimeException. If we are extending the java.lang.Exception then our custom exception will be checked exception and if we are extending the java.lang.RuntimeException then our custom exception will be unchecked exception.
  • If we want to store some data then we can define some variable and to initialize the variable we can define the constructor.
  • To initialize the message for the exception we can we can invoke the super constructor with the string parameter.
  • We can override the method inherited from super class.

Example of user defined exception in java:-

public class CheckBalanceException extends Exception {

	private static final long serialVersionUID = 1L;
	
	public CheckBalanceException(String message){
		super(message);
	}	
}
public class CheckBalance {

	public static void main(String args[]) throws CheckBalanceException{
		int balance = 1000;
		int withdraw = 1100;
		
		if(withdraw > balance){
			throw new CheckBalanceException("insufficient balance");
		}
		else{
			System.out.println("sufficient balance");
		}
	}
}

output:-
User defined exception in java

Leave a Comment