Java Interview Questions

30 Questions
Java

Java

Web DevelopmentBackend

Question 26

How do you create a custom exception in Java?

Answer:

Creating a custom exception in Java involves defining a new class that extends either Exception (for checked exceptions) or RuntimeException (for unchecked exceptions). This allows you to create specific exceptions that are relevant to your application's domain and provide more meaningful error handling.

Steps to Create a Custom Exception

  1. Define a Class: Create a new class that extends Exception or RuntimeException.
  2. Constructors: Provide constructors that allow different ways to instantiate the exception.
  3. Optional Methods: You can add additional methods or fields to provide more context for the exception.

Example of Creating a Custom Checked Exception

To create a custom checked exception, extend the Exception class:

// Step 1: Define the class
public class InvalidUserInputException extends Exception {
    
    // Step 2: Provide constructors

    // Default constructor
    public InvalidUserInputException() {
        super();
    }

    // Constructor that accepts a message
    public InvalidUserInputException(String message) {
        super(message);
    }

    // Constructor that accepts a message and a cause
    public InvalidUserInputException(String message, Throwable cause) {
        super(message, cause);
    }

    // Constructor that accepts a cause
    public InvalidUserInputException(Throwable cause) {
        super(cause);
    }
}

Example of Creating a Custom Unchecked Exception

To create a custom unchecked exception, extend the RuntimeException class:

// Step 1: Define the class
public class InvalidConfigurationException extends RuntimeException {
    
    // Step 2: Provide constructors

    // Default constructor
    public InvalidConfigurationException() {
        super();
    }

    // Constructor that accepts a message
    public InvalidConfigurationException(String message) {
        super(message);
    }

    // Constructor that accepts a message and a cause
    public InvalidConfigurationException(String message, Throwable cause) {
        super(message, cause);
    }

    // Constructor that accepts a cause
    public InvalidConfigurationException(Throwable cause) {
        super(cause);
    }
}

Using Custom Exceptions

Once you have defined your custom exceptions, you can use them in your code to handle specific error conditions.

Example Usage of a Custom Checked Exception:

public class UserInputHandler {
    public void validateInput(String input) throws InvalidUserInputException {
        if (input == null || input.isEmpty()) {
            throw new InvalidUserInputException("Input cannot be null or empty");
        }
        // Further validation logic
    }

    public static void main(String[] args) {
        UserInputHandler handler = new UserInputHandler();
        try {
            handler.validateInput("");
        } catch (InvalidUserInputException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }
}

Example Usage of a Custom Unchecked Exception:

public class ConfigurationLoader {
    public void loadConfiguration(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            throw new InvalidConfigurationException("Configuration file path cannot be null or empty");
        }
        // Further configuration loading logic
    }

    public static void main(String[] args) {
        ConfigurationLoader loader = new ConfigurationLoader();
        loader.loadConfiguration(""); // This will throw an InvalidConfigurationException
    }
}

Key Points

  1. Inheritance: Decide whether your custom exception should be checked or unchecked by extending Exception (checked) or RuntimeException (unchecked).
  2. Constructors: Provide constructors to allow various ways of instantiating the exception.
  3. Usage: Throw your custom exceptions in appropriate places to signal specific error conditions.
  4. Handling: Catch and handle custom exceptions where necessary to provide meaningful error messages or recovery options.

Conclusion

Creating custom exceptions in Java allows you to define error conditions specific to your application's domain, leading to more robust and maintainable code. By extending Exception or RuntimeException, you can control whether your exception is checked or unchecked, and provide detailed information about the error through constructors and additional methods. This helps in writing clear, self-explanatory, and well-organized error handling code.

Recent job openings