Custom (User Defined) Exception In Java - Java Tutorial

Custom (User Defined) Exception In Java

BLUF: Mastering Custom (User Defined) Exception In Java is a key requirement for any Java developer. This lesson breaks down the object-oriented principles and syntax required to use this concept in real-world applications.
Write Once, Run Anywhere Tip: Custom (User Defined) Exception In Java

Java's versatility is unmatched. Learn how Custom (User Defined) Exception In Java fits into the Java ecosystem and improves your code structure in the tutorial below.

In Java, developers have the ability to define their own exceptions to cater to specific needs within an application. These custom exceptions are subclasses of the Exception class and are commonly referred to as user-defined exceptions. Essentially, Java custom exceptions allow for the customization of exceptions based on the user's needs.

This specific exception is an extension of either the Exception class or the RuntimeException class, which is typically used for unchecked exceptions. By utilizing this custom exception, developers have the ability to create their own unique exceptions along with custom error messages.

Example of Custom Exception

In the given scenario, an instance is demonstrated where a personalized exception called IncorrectFilenameException has been generated.

Example

public class WrongFileNameException extends Exception {  

    public WrongFileNameException(String errorMessage) {  

    super(errorMessage);  

    }  

}

In this case, a string was provided to the superclass constructor, specifically the Exception class, which is retrievable by calling the getMessage method on the instantiated object.

Note: We need to write the constructor that takes a String as the error message, and it is called the parent class constructor.

Why use custom exceptions?

In Java, exceptions encompass a wide range of common exception types that can arise while a program is running. Despite this, there are occasions when it becomes necessary to define custom exceptions.

The following are a few of the reasons to use custom exceptions:

  • It represents application-specific errors.
  • To catch and provide specific treatment to a subset of existing Java exceptions.
  • Business Logic Exceptions: These are the exceptions related to business logic and workflow. It is useful for users and developers to understand the exact problem in a meaningful way.
  • It provides clear, descriptive error messages for better debugging.
  • Creating a Custom Exception

To create a custom exception, follow these steps:

  • First, extend the Exception class (for checked exceptions) that belongs to the java.lang package or the RuntimeException class (for unchecked exceptions).
  • Initialize the exception with custom messages using the constructor.
  • It is optional to add methods to provide additional details about the exception.

Let's see an example of a Java custom exception.

Example 1: Creating a Custom Exception

The Java code snippet below demonstrates the use of a string argument in the constructor of the InvalidAgeException class. This argument is then forwarded to the constructor of the Exception superclass by invoking the super method. It's worth noting that the Exception class constructor can function without any parameters, and invoking the super method in this context is optional.

Example

Example

// class representing custom exception  

class InvalidAgeException extends Exception  {  

    public InvalidAgeException (String str)  {  

        // calling the constructor of the parent Exception  

        super(str);  

    }  

}  

// class that uses custom exception InvalidAgeException  

public class Main {  

    // method to check the age  

    static void validate (int age) throws InvalidAgeException {    

       if(age < 18){  

        // throw an object of user user-defined exception  

        throw new InvalidAgeException("age is not valid to vote");    

    }  

       else {   

        System.out.println("welcome to vote");   

        }   

     }    

    // main method  

    public static void main(String args[])   {  

        try    {  

            // calling the method   

            validate(13);  

        }  

        catch (InvalidAgeException ex)   {  

            System.out.println("Caught the exception");  

            // printing the message from the InvalidAgeException object  

            System.out.println("An exception occurred: " + ex);  

        }  

        System.out.println("rest of the code...");    

    }  

}

Output:

Output

Caught the exception

An exception occurred: InvalidAgeException: age is not valid to vote

rest of the code...

Example 2: Caught an Exception

Example

Example

// class representing custom exception  

class MyCustomException extends Exception  {  

}  

// class that uses custom exception MyCustomException  

public class Main  {  

    // main method  

    public static void main(String args[])   {  

        try  {  

            // throw an object of user user-defined exception  

            throw new MyCustomException();  

        }  

        catch (MyCustomException ex)  {  

            System.out.println("Caught the exception");  

            System.out.println(ex.getMessage());  

        }  

        System.out.println("rest of the code...");    

    }  

}

Output:

Output

Caught the exception

null

rest of the code...

Java Custom Exception MCQs

  1. Which of the following is true about custom exceptions in Java?
  • Custom exceptions must extend the Throwable class directly.
  • Custom exceptions can only be checked exceptions.
  • Custom exceptions must extend the Exception class or its subclasses.
  • Java does not allow the creation of custom exceptions.

Explanation: In Java, custom exceptions are typically created by extending the Exception class (checked exceptions) or the RuntimeException (unchecked exceptions). They do not need to extend Throwable directly.

  1. Which of the following methods is used to retrieve the message passed to the custom exception?
  • printMessage
  • getMsg
  • retrieveMessage
  • getMessage

Explanation: The getMessage method is inherited from the Throwable class and is used to return the detailed message of the exception.

  1. What happens if we do not call super inside the custom exception constructor?
  • Compilation error
  • Runtime error
  • It will compile and run, but the exception message will be null
  • JVM will not allow custom exception creation

Explanation: If super is not explicitly called with a message, the base class constructor without arguments is called by default, and the exception message will be an empty string or null, depending on the constructor behavior of the base exception class.

  1. Why do we use custom exceptions in Java?
  • To handle application-specific and business logic-related exceptions
  • Java does not support built-in exceptions
  • Custom exceptions are faster than built-in exceptions
  • To reduce memory usage

Explanation: Custom exceptions are used to capture and clearly express domain-specific or business logic errors that may not be clearly conveyed using built-in exceptions.

  1. In the custom exception class InvalidAgeException, what is the purpose of calling super(str) in its constructor?
  • It creates a new object of the Exception class.
  • It passes the error message to the constructor of the Exception class.
  • It prints the error message to the console.
  • It stops the execution of the program.

The super(str) function is utilized to send the error message to the superclass Exception, enabling the retrieval of the message at a later time by using getMessage.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience