Java – User-defined Exception or Custom Exception

In this article, we will discuss user-defined exception or custom exception or customized exception in detail

So far, whatever example we have covered in the earlier articles that are all based on pre-defined exception in Java. For example, we have seen below exception

  • Exception
  • NullPointerException
  • ArithmeticException
  • ArrayIndexOutOfBoundsException
  • NumberFormatException
  • IOException
  • FileNotFoundException
  • Error
  • etc

Each one of the above mentioned exception has its own definition like, whenever we are checking length on a null string, then NullPointerException is thrown with below details,

  • Name of the Exception
  • Description of the Exception
  • Location at which exception is thrown (i.e.; stack trace)

User scenario:

  • Now, assume a scenario where we want to raise/throw an exception whenever a person tries to obtain a driving license by registering with an invalid-age or under-age
  • Generally, to obtain a driving license age should be 18 years old
  • And if someone tries to register for driving license with age less than 18 then we should throw/raise an exception stating “To obtain a driving license age should be more than 18 years old
  • This type of description isn’t available in the list of pre-defined exception
  • So to throw this type of exception, programmer can define user-defined exception or custom exception or customized exception

1. User-defined or Custom Exception:

  • Let us define one User-defined exception for Invalid age
  • and we will use this exception in the subsequent demo example for throwing

InvalidAgeForDrivingLicenseException.java

package in.bench.resources.exception.handling;

public class InvalidAgeForDrivingLicenseException
extends Exception {

	// member variable for Exception Description
	String expDescription;

	// public constructor with String argument
	InvalidAgeForDrivingLicenseException(String expDescription) {

		super(expDescription);
	}
}

RegisterForDrivingLicenseDemo.java

package in.bench.resources.exception.handling;

import java.util.Scanner;

public class RegisterForDrivingLicenseDemo {

	// main() method - JVM execution starts here
	public static void main(String[] args) {

		System.out.println("Enter your Age for registering"
				+ " driving license");

		// to take input from user
		Scanner scanner = new Scanner(System.in);
		int userAge = scanner.nextInt();

		// try-catch blocks for User-defined Exception
		try {

			if(userAge < 0) {

				throw new InvalidAgeForDrivingLicenseException(
						"Enter a VALID age for"
								+ " obtaining driving license");
			}
			else if(userAge < 18) {

				throw new InvalidAgeForDrivingLicenseException(
						"To obtain a driving license age should"
								+ " be more than 18 years old");
			}
			System.out.println(
					"Approved to apply for driving license !!");
		}
		catch(InvalidAgeForDrivingLicenseException iafdlex) {
			System.out.println(iafdlex);
		}
	}
}

Output:

Enter your Age for registering driving license
16
in.bench.resources.exception.handling
	.InvalidAgeForDrivingLicenseException:
To obtain a driving license age should be more than 18 years old

Explanation:

  • When above program executed, then console waits for users to enter age for registering driving license
  • When user enters age as 16 (which is below than the threshold age of 18)
  • Then an explicit user-defined exception is thrown with an error description stating “To obtain a driving license age should be more than 18 years old
  • Likewise, if user enters age as negative-value, then same user-defined exception with respective description will be thrown explicitly
  • Happy Scenario: when user enters any age above 18, then it will print success message for successful registration for driving license

From above example, there are certain points to be questioned & respectively answered,

Q) Whether it is must to extend Exception class for User-defined Exception ?

  • It is very must to extend one of the exception type in the Exception hierarchy
  • otherwise it won’t act as User-defined exception rather plain-old-java-object

Q) If extending Exception is must, then what type of Exception need to be extended (i.e.; whether to extend checked exception or unchecked exception ?)

  • To define User-defined exception, any one of the Exception-type from Exception hierarchy needs to be extended
  • Well it can be checked exception or unchecked exception

Q) What is the significance of extending checked exception ?

Q) What is the significance of extending unchecked exception ?

  • Whenever user-defined exception extends unchecked exception,
  • then compiler never forces programmer to handle exception
  • Rather, it is the choice of programmer to handle either by try-catch block or declaring this exception using throws clause

Q) Whether public 1-argument constructor of String-type must always be provided ?

  • Though, it isn’t strict to provide public 1-argument Constructor of String-type
  • but providing will help programmer to pass user-defined error/exception description along with the User-defined exception-type

Q) What happens, if we don’t provide public 1-argument constructor of String type ?

  • By not providing public 1-argument Constructor of String type, stops programmer to define user-defined error/exception description whenever explicit User-defined exception is thrown using throw keyword

Q) Explain how user-defined exception’s description is made available to printStackTrace(); method (as this method is defined inside Throwable class –> top of Exception hierarchy)

2. Rule for User-defined exception or Custom exception:

2.1 Unchecked User-defined exception:

  • Example to showcase User-defined exception which extends unchecked-exception

InvalidAgeForDrivingLicenseException.java

package in.bench.resources.exception.handling;

public class InvalidAgeForDrivingLicenseException
extends RuntimeException {

	// member variable for Exception Description
	String expDescription;

	// public constructor with String argument
	InvalidAgeForDrivingLicenseException(String expDescription) {

		super(expDescription);
	}
}

RegisterForDrivingLicenseDemo.java

Explanation:

In the above example,

  • User-defined exception i.e.; InvalidAgeForDrivingLicenseException is extending RuntimeException which is an unchecked exception
  • Therefore, compiler doesn’t forces/tells to handle it i.e.; it is a choice of programmer who is using this exception either can handle it or NOT
  • Programmer can handle unchecked exception either by try-catch blocks or declare using throws clause
  • From above screen-capture, it is seen that whenever User-defined exceptionInvalidAgeForDrivingLicenseException” is raised/thrown explicitly by using throw keyword, then programmer neither handled it using try-catch blocks nor declared using throws clause and also compiler doesn’t complains about it with any compile-time error
  • This can be considered as an advantage, as it never forces to handle it

2.2 Checked User-defined exception:

  • Example to showcase User-defined exception which extends checked-exception

InvalidAgeForDrivingLicenseException.java

package in.bench.resources.exception.handling;

import java.io.IOException;

public class InvalidAgeForDrivingLicenseException
extends IOException {

	// member variable for Exception Description
	String expDescription;

	// public constructor with String argument
	InvalidAgeForDrivingLicenseException(String expDescription) {

		super(expDescription);
	}
}

RegisterForDrivingLicenseDemo.java

Explanation:

In the above example,

  • Assumption: just for demo purpose we have extended IOException which is a checked exception, to showcase what happens whenever user-defined exception extending checked-exception is thrown explicitly
  • As it can be seen from screen-capture above, compiler raises compile-time error stating “Unhandled exception type InvalidAgeForDrivingLicenseException
  • And forces programmer to handle by providing 2 options
  • Option 1: declare user-defined exception using throws clause (Add throws declaration)
  • Option 2: handle user-defined exception using try-catch blocks (Surround with try/catch)
  • Let us re-write program by surrounding with try-catch block for exception handling (i.e.; basically exception handling for solving compile-time error)

RegisterForDrivingLicenseDemo.java

3. Conclusion:

  • Thus, programmer can create application specific exception depending on the business scenario which is called as user-defined exception or custom exception
  • These exceptions can be checked exception or unchecked exception depending on what type of exception is being extended for creating user-defined exception or customized exception

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 7 - try-with-resources with examples
Java - 5 important keywords in Exception handling