What is user defined exception?

Java allows us to create our own custom exception by extending any built-in exception class, these type of exception are known as a user-defined or custom exception. The user-defined exception is helpful to customize the exception according to application requirement.

How to create a custom exception?

To create a Java custom exception we need to extend any built-in or none final exception class. As we already know that class Exception is the most base class of any other built-in exception. Following is the example that shows how you can extend the class Exception to create a user-defined/custom exception.

public class MyException extends Exception {

    public MyException() {
        super("Oops custom exception occured.");
    }

}

Built-in exception classes

Some of the built-in exception available in Java –

  1. ArrayIndexOutOfBoundException
  2. StringIndexOutOfBoundsException
  3. ClassNotFoundException
  4. NumberFormatException
  5. FileNotFoundException
  6. NullPointerException
  7. RuntimeException
  8. IOException
  9. etc…

Different examples

Following are the different examples of user-defined exception try and modify them to better understand.

Example 1

In the below-shown example program, we are authenticating a user using if-else with username “user” and password “pass”. If the user provides other than this credentials we will throw InvalidUserException which is a user-defined exception.

public class CustomExceptionExample1 {

    // A custom exception class
    public static class InvalidUserException extends Exception {

        public InvalidUserException() {
            super("Invalid username / password provided!");
        }

    }

    public static void main(String[] args) {

        // A invalid username
        String username = "john";

        String password = "pass";

        try {

            if (username.equals("user") && password.equals("pass")) {

                System.out.println("Authenticated successfully!");

            } else {

                throw new InvalidUserException();
            }

        } catch (InvalidUserException e) {
            System.out.println(e);
        }
    }
}

Example 2

In the following example program, a custom exception class is created to handle invalid number exception. By default, the NumberFormatException (unchecked exception) class is thrown while parsing an invalid number.

public class CustomExceptionExample2 {

    // A custom exception to handle invalid number exception
    public static class InvalidNumberException extends Exception {

        public InvalidNumberException() {
            super("Please provide a valid number!");
        }

    }

    public static int addNumber(String strA, String strB) throws InvalidNumberException {

        try {

            int numA = Integer.parseInt(strA);
            int numB = Integer.parseInt(strB);

            return numA + numB;

            /* 
             If NumberFormatException raise then, 
             rethrow the InvalidNumberException
             */
        } catch (NumberFormatException e) {
            throw new InvalidNumberException();
        }
    }

    public static void main(String[] args) {

        try {
            String strA = "100";

            // A invalid number
            String strB = "100_Studyfied";

            addNumber(strA, strB);

        } catch (InvalidNumberException ex) {
            System.out.println(ex.getMessage());
        }

    }
}