Custom Exceptions in Java


In Java, exceptions are used to handle errors and exceptional conditions during the execution of a program. Sometimes, the built-in exceptions are not enough to represent the specific error conditions in your application. In such cases, you can create your own exception classes. These are called Custom Exceptions.

1. What is a Custom Exception?

A custom exception is an exception that is defined by the user to handle specific situations that the built-in exceptions cannot address. To create a custom exception, you need to extend one of the existing exception classes in Java. Typically, custom exceptions extend Exception or one of its subclasses.

Syntax for Creating Custom Exception

    class CustomException extends Exception {
        public CustomException(String message) {
            super(message);
        }
    }
        

2. Steps to Create and Use Custom Exceptions

To create and use a custom exception, follow these steps:

  1. Create a new class that extends the Exception class or its subclass.
  2. Define a constructor in the custom exception class to initialize the exception message.
  3. Throw the custom exception in the desired place in your program using the throw keyword.
  4. Catch and handle the custom exception using a try-catch block.

3. Example of Creating and Using a Custom Exception

In this example, we will create a custom exception called AgeException to handle invalid age input. If the age entered is less than 18, the exception will be thrown.

    class AgeException extends Exception {
        public AgeException(String message) {
            super(message);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            try {
                checkAge(15);  // Passing an invalid age
            } catch (AgeException e) {
                System.out.println("Caught exception: " + e.getMessage());
            }
        }
    
        static void checkAge(int age) throws AgeException {
            if (age < 18) {
                throw new AgeException("Age must be 18 or older");
            } else {
                System.out.println("Age is valid: " + age);
            }
        }
    }
        

Output:

    Caught exception: Age must be 18 or older
        

Explanation:

  • The AgeException class extends the Exception class and has a constructor to pass the error message.
  • The checkAge method checks if the entered age is less than 18 and throws the AgeException with an appropriate message.
  • The main method calls checkAge and catches the exception using a try-catch block, printing the exception message when it is caught.

4. Adding Additional Information to Custom Exceptions

You can add more information to your custom exception, such as error codes or other fields, to make it more informative. This can be helpful for debugging or logging purposes.

    class AgeException extends Exception {
        private int errorCode;
    
        public AgeException(String message, int errorCode) {
            super(message);
            this.errorCode = errorCode;
        }
    
        public int getErrorCode() {
            return errorCode;
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            try {
                checkAge(15);  // Passing an invalid age
            } catch (AgeException e) {
                System.out.println("Caught exception: " + e.getMessage() + " with error code: " + e.getErrorCode());
            }
        }
    
        static void checkAge(int age) throws AgeException {
            if (age < 18) {
                throw new AgeException("Age must be 18 or older", 101);
            } else {
                System.out.println("Age is valid: " + age);
            }
        }
    }
        

Output:

    Caught exception: Age must be 18 or older with error code: 101
        

Explanation:

  • The custom exception AgeException now includes an additional errorCode field.
  • The checkAge method throws the exception with both a message and an error code when the age is less than 18.
  • The main method catches the exception and prints both the error message and the error code.

5. Conclusion

Custom exceptions in Java provide a powerful way to handle specific error conditions in your programs. By extending the built-in Exception class, you can create meaningful exceptions that make your program more robust and easier to understand. Custom exceptions are particularly useful when the standard exceptions do not provide enough information about the error, or when you need to handle specific application-level conditions.





Advertisement