LeetCampus
Interview Question

Write a Java program to create and throw custom exceptions.

July 24, 2025
0 views
Difficulty: Medium
Popularity: Common
Share on

Question Explanation

Custom exceptions in Java allow developers to create their own exceptions tailored to specific needs, enhancing error handling in applications. Interviewers often ask about custom exceptions to assess a candidate's understanding of exception handling, the importance of clean code, and the ability to create maintainable software. This question tests the candidate's knowledge of inheritance, encapsulation, and polymorphism, which are fundamental concepts in object-oriented programming. Understanding how to create and throw custom exceptions demonstrates a candidate's ability to manage error handling effectively, leading to more robust applications. Furthermore, it showcases the candidate's capability to identify when a standard exception isn't sufficient, thus creating a better user experience. Interviewers may also look for an understanding of the Java exception hierarchy, as well as best practices for exception handling, such as proper documentation and meaningful messages. In real-world applications, effective use of custom exceptions can lead to improved debugging and clearer code semantics. Candidates should be wary of common pitfalls, such as overusing exceptions or failing to document them adequately, which can lead to poor maintainability.

Sample Answers

Example 1: Creating a Custom Exception

To create a custom exception in Java, you need to extend the Exception class. Here's a simple example:

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

In this example, InvalidAgeException is our custom exception. It takes a string message which can be used to provide additional information about the error. To throw this exception, you might have a method that checks age:

public void setAge(int age) throws InvalidAgeException {
    if (age < 0 || age > 150) {
        throw new InvalidAgeException("Age must be between 0 and 150.");
    }
    // Set age logic here
}

This method throws our custom exception if the age is invalid. This approach allows for clearer, more meaningful error handling in applications.

Example 2: Catching Custom Exceptions

Once you have defined a custom exception, handling it is crucial. You can catch it using a try-catch block. Here’s how you can catch the InvalidAgeException:

public class Main {
    public static void main(String[] args) {
        try {
            setAge(200);
        } catch (InvalidAgeException e) {
            System.out.println(e.getMessage());
        }
    }
}

In this example, when setAge(200) is called, it throws an InvalidAgeException because 200 is not a valid age. The catch block captures this exception and prints the error message. This method of handling allows the program to continue running instead of crashing, providing a better user experience. Always ensure to log the exception for debugging purposes.

Example 3: Best Practices for Custom Exceptions

When creating custom exceptions, adhering to best practices is essential for maintainability. Here are some recommended practices:

  • Meaningful Names: Name your exceptions clearly to reflect the error context, e.g., InvalidAgeException.
  • Documentation: Always document your custom exceptions, explaining when and why to use them.
  • Extending RuntimeException: If the exception is unchecked, consider extending RuntimeException instead of Exception to avoid mandatory try-catch blocks.

Example:

public class InvalidInputException extends RuntimeException {
    public InvalidInputException(String message) {
        super(message);
    }
}

Using unchecked exceptions can simplify code, especially for validation errors. Remember to provide useful messages and consider the impact on the calling code.

Keywords

Javacustom exceptionsexception handlingsoftware engineeringOOP

Ready to practice more questions?

Explore our collection of technical interview questions from top companies.

View All Questions