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 ?
- Whenever user-defined exception extends checked exception,
- then compiler forces/tells programmer to handle this exception either by try-catch blocks or declaring this exception using throws clause
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)
- To make user-defined error/exception description available to printStackTrace() method of Throwable class,
- just provide call to super() constructor using super keyword along with user-defined error/exception description of String-type as its argument
2. Rule for User-defined exception or Custom exception:
- throw keyword is used to throw User-defined exception explicitly
- Whenever User-defined exception is created, then it is must to extend one of the exception type from the Exception hierarchy
- User-defined exception extending checked exception forces programmer to handle either by try-catch block or declaring using throws clause
- User-defined exception extending unchecked exception allows choice to programmer to handle the exception either by try-catch block or declaring using throws clause
- Always provide public 1-arguemnt Constructor of String-type
- Always, provide one statement inside constructor i.e.; call to super constructor by passing string argument
- This helps to supply error/exception description available to printStackTrace() method of Throwable class through Constructor chaining process
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 exception “InvalidAgeForDrivingLicenseException” 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:
- Java – Exception Handling
- Java – Exception Hierarchy
- Java – 5 important keywords in Java Exception handling
- Java – Runtime mechanism, what happens when exception is thrown ?
- Java – Checked Exception v/s Unchecked Exception
- Java – Exception propagation
- Java – try-catch block
- Java – finally block
- Java – try with multiple catch blocks
- Java – Nested try-catch block
- Java – Returning value from method having try-catch-finally blocks
- Java – return statement with finally block
- Java – final v/s finally v/s finalize
- Java – Various methods to print exception information
- Java – throw keyword
- Java – throws keyword
- Java – throw v/s throws
- Java – Difference between throws clause and try-catch-finally block
- Java – Rules for Exception handling w.r.t Method Overriding
- Java – User-defined or Custom exception
- Java – Difference between ClassNotFoundException v/s NoClassDefFoundError
- Java – Top Exception and Error
- Java – Interview question and answers on Exception Handling
- Java 7 – try with resources
- Java 7 – multi-catch block
References:
- http://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/declaring.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/
- https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/Error.html
- https://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/ArithmeticException.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html
- http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
- http://www.oracle.com/technetwork/java/effective-exceptions-092345.html
- http://otfried.org/courses/cs206/slides/slides-stackframes.pdf
Happy Coding !!
Happy Learning !!