June 16, 2022

How to Create Custom Exception Class in Java

In Java exception handling there are lots of exception classes that can be used for handling exceptions. Though some times you may not find an appropriate exception class that clearly represents the exception thrown from your code, in such scenario you may choose to create your own custom exception class. In this post we’ll see how to create custom exception class in Java.

When to opt for a user defined exception class

Java docs clearly specify the scenario when you may want to create your own custom exception class in Java. You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's.

  • Do you need an exception type that isn't represented by those in the Java platform?
  • Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
  • Does your code throw more than one related exception?
  • If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?

Creating custom exception class in Java

In order to create your own exception class you may extend either Exception class or RunTimeException class.

If you want your Java custom exception to be a checked exception, where it is enforced that the exception is either handled using try-catch block or declared using throws clause, you need to extend the Exception class.

If you want your custom exception to be an unchecked exception, where you don't need to enclose code with in try-catch block or declare the exception, you need to extend the RuntimeException class.

Java example code to create custom exception class

Here is a simple example to show how to create custom exception class in Java.

Let’s say you have an application where you don’t want number greater than 100 to be passed. In case number greater than 100 is passed you want to throw an InvalidNumberException which is a custom exception class.

InvalidNumberException is implemented as an unchecked exception in the example code by extending the RuntimeException class.

InvalidNumberException.java
public class InvalidNumberException extends RuntimeException {

  private int num;
  // Demonstrating all the 4 constructors
  InvalidNumberException(){
    super();
  }
  InvalidNumberException(int num){
    this.num = num;
  }
  InvalidNumberException(int num, String msg){
    super(msg);
    this.num = num;
  }
  InvalidNumberException(int num, String msg, Throwable cause){
    super(msg, cause);
    this.num = num;
  }

  public String toString() {
    return "InvalidNumberException for number " + num;				
  }

  public String getMessage() {
    return "InvalidNumberException for number " + num;				
  }
}
MyExceptionDemo.java
public class MyExceptionDemo {
  public static void main(String[] args) {
    process(5);
    process(200);
  }
	
  public static void process(int num){
    System.out.println("In method process- " + num);
    if (num > 100){
      throw new InvalidNumberException(num);
    }
  }
}
Output
In method process- 5
In method process- 200
Exception in thread "main" InvalidNumberException for number 200
at com.knpcode.MyExceptionDemo.process(MyExceptionDemo.java:14)
at com.knpcode.MyExceptionDemo.main(MyExceptionDemo.java:7)

Custom exception as checked or unchecked

In order to decide between checked exception Vs unchecked exception, you must follow the following rule.

  • If client can take some action to recover from an exception, make your custom exception as a checked exception.
  • If a client cannot do anything to recover from the exception, make your custom exception an unchecked exception.

As example– If all that is done when an exception is thrown is to log the error and no attempt to recover from that error then better to go with RunTimeException.

That's all for the topic How to Create Custom Exception Class in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment