Creating custom exceptions in Java

Java allows programmers to create their own Exceptions. To create and exception, you should inherit from the exception closest to what you wish to create. Following is a generic example to show how to create and use a custom exception.

public class CustomException extends Exception
{
   String ex;
   public CustomException() {
       super();
       ex = "Something is empty";
   }

   public CustomException(String msg) {
       super(msg);
       ex = msg;
   }

   public String getError() {
       return ex;
   }
}

This exception class provides a no argument constructor which prints a default message, "Something is empty". The second constructor returns the message in the throw statement of the calling method. getError() is a callable function that returns the Exception message.

public class TestCustomException
{
   public static void main(String[] args) {
       try {
           f();
       } catch (CustomException e) {
           System.out.println(e.getError());
       }

       try {
           g();
       } catch (CustomException e) {
           System.out.println(e.getError());
       }
   }

   public static void f() throws CustomException { 
       throw new CustomException();
   }

   public static void g() throws CustomException { 
       throw new CustomException("empty");
   }
}

output

Something is empty
empty

Method f() throws a CustomException without any argument, so the default value message "Something is empty" is returned. Method g() throws a CustomException with a String argument.

Technologies: