Java Exception Handling Interview Questions and Answers

In this article, we will discuss important Java Exception Handling interview questions and answers.
Check out complete beginner to expert in-depth exception handling tutorial in Java
Let's explore below questions that are likely to appear in technical interviews for Java developers, regarding exceptions.
  1. What is an Exception in Java?
  2. How Exception Handling Works in Java
  3. What are the Exception Handling Keywords in Java?
  4. What is the purpose of the throw and throws keywords?
  5. How can you handle an exception?
  6. Explain Java Exception Hierarchy?
  7. How can you catch multiple exceptions?
  8. What is the difference between Checked and Unchecked Exceptions in Java?
  9. What is the difference between the throw and throws keywords in Java?
  10. What is the difference between an exception and an error?
  11. What is OutOfMemoryError in Java?
  12. What are Chained Exceptions in Java?
  13. How to write custom exceptions in Java?
  14. What is the difference between final, finally, and finalize in Java?
  15. What happens when an exception is thrown by the main method?
  16. What is a try-with-resources statement?
  17. What is a stack trace and how does it relate to an exception?
  18. What are the Advantages of Java Exceptions?
  19. Can you throw any exception inside a lambda expression’s body?
  20. What are the rules we need to follow when overriding a method that throws an exception?
  21. Java Exception Handling Best Practices

1. What is an Exception in Java?

An exception is an unwanted or unexpected event that occurs during the execution of a program, which may interrupt the normal flow of the program. 

In Java, exceptions are represented as objects of the Exception class or its sub-classes.

Read more about Exceptions in Java at Java Exception Handling Tutorial

2. How Exception Handling Works in Java

The below steps demonstrate how exception handling works in Java:

Step 1: When an error occurs within a method, the method creates an object and hands it off to the runtime system this object is called an exception object. The exception object contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception

Step 2: After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack. The following diagram shows the call stack of three method calls, where the first method called has the exception handler.
    Step 3: The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. 

    An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.

    Step 4: The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the following diagram, the runtime system (and, consequently, the program) terminates.

    3. What are the Exception Handling Keywords in Java?

    Java exception handling is managed via five keywords -
    1. try: Enclose the code that might throw an exception within a try block. If an exception occurs within the try block, that exception is handled by an exception handler associated with it. The try block contains at least one catch block or finally block.

    2. catchJava catch block is used to handle the Exception. It must be used after the try block only. You can use multiple catch block with a single try.

    3. throw: Sometimes we explicitly want to create an exception object and then throw it to halt the normal processing of the program. throw keyword is used to throw an exception to the run-time to handle it.

    4. throws: When we are throwing any checked exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to its caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with the main() method also.

    5. finally: finally block is optional and can be used only with a try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed so we can use finally block. finally block gets executed always, whether exception occurrs or not.

    This diagram summaries usage of these keywords.
    Read more about all five keywords at Exception Handling Keywords in Java with Examples.

    4. What is the purpose of the throw and throws keywords?

    The throws keyword is used to specify that a method may raise an exception during its execution. It enforces explicit exception handling when calling a method:
    public void simpleMethod() throws Exception {
        // ...
    }
    The throw keyword allows us to throw an exception object to interrupt the normal flow of the program. This is most commonly used when a program fails to satisfy a given condition:
    if (task.isTooComplicated()) {
        throw new TooComplicatedException("The task is too complicated");
    }
    Read more about throw keyword at Java throw Keyword with Example
    Read more about throws keyword at Java throws Keyword with Example

    5. How can you handle an exception?

    By using a try-catch-finally statement:
    try {
        // ...
    } catch (ExceptionType1 ex) {
        // ...
    } catch (ExceptionType2 ex) {
        // ...
    } finally {
        // ...
    }
    The block of code in which an exception may occur is enclosed in a try block. This block is also called “protected” or “guarded” code.
    If an exception occurs, the catch block that matches the exception being thrown is executed, if not, all catch blocks are ignored.
    The finally block is always executed after the try block exits, whether an exception was thrown or not inside it.

    Read more about how to handle exceptions in Java at Java Exception Handling Tutorial

    6. Explain Java Exception Hierarchy?

    The objects that inherit from the Throwable class include direct descendants (objects that inherit directly from the Throwable class) and indirect descendants (objects that inherit from children or grandchildren of the Throwable class).
    Throwable has two direct descendants:
    1. Error Class
    2. Exception Class
    The figure below illustrates the class hierarchy of the Throwable class and its most significant subclasses.

    Error Class: When a dynamic linking failure or other hard failures in the Java virtual machine occurs, the virtual machine throws an Error.
    Examples - VirtualMachineError, OutOfMemoryError, UnKnownError, StackOverflowError etc.

    Exception Class: Most programs throw and catch objects that derive from the Exception class. An Exception indicates that a problem occurred, but it is not a serious system problem. For example FileNotFoundException. We should catch this exception and provide a useful message to a user and log it properly for debugging purpose. Exception class is the parent class of all Checked Exceptions.

    RuntimeException Class: One Exception subclass, RuntimeException, is reserved for exceptions that indicate an incorrect use of an API. An example of a runtime exception is NullPointerException, which occurs when a method tries to access a member of an object through a null reference.

    Read more about Exception Hierarchy in Java at Exceptions Hierarchy in Java

    7. How can you catch multiple exceptions?

    There are three ways of handling multiple exceptions in a block of code.
    The first is to use a catch block that can handle all exception types being thrown:
    try {
        // ...
    } catch (Exception ex) {
        // ...
    }
    You should keep in mind that the recommended practice is to use exception handlers that are as accurate as possible.
    Exception handlers that are too broad can make your code more error-prone, catch exceptions that weren’t anticipated, and cause unexpected behavior in your program.
    The second way is implementing multiple catch blocks:
    try {
        // ...
    } catch (FileNotFoundException ex) {
        // ...
    } catch (EOFException ex) {
        // ...
    }
    Note that, if the exceptions have an inheritance relationship; the child type must come first and the parent type later. If we fail to do this, it will result in a compilation error.
    The third is to use a multi-catch block:
    try {
        // ...
    } catch (FileNotFoundException | EOFException ex) {
        // ...
    }
    This feature, first introduced in Java 7; reduces code duplication and makes it easier to maintain.

    Read more at Java try/catch Block with Examples

    8. What is the difference between Checked and Unchecked Exception in Java?

    1. Checked Exceptions should be handled in the code using try-catch block or else method should use throws keyword to let the caller know about the checked exceptions that might be thrown from the method. Unchecked Exceptions are not required to be handled in the program or to mention them in the throws clause of the method.

    2. Exception  class is the superclass of all checked exceptions whereas RuntimeException is the superclass of all unchecked exceptions. Note that RuntimeException is the child class of Exception.

    3. Checked exceptions are error scenarios that require to be handled in the code, or else you will get compile time error. For example, if you use FileReader to read a file, it throws FileNotFoundException and we must catch it in the try-catch block or throw it again to the caller method. Unchecked exceptions are mostly caused by poor programming, for example, NullPointerException when invoking a method on an object reference without making sure that it’s not null. For example, I can write a method to remove all the vowels from the string. It’s the caller responsibility to make sure not to pass a null string. I might change the method to handle these scenarios but ideally, the caller should take care of this.

    4. Checked and unchecked exceptions are also known as compile-time and run-time exceptions respectively.

    9. What is the difference between throw and throws keyword in Java?

    throws keyword is used with method signature to declare the exceptions that the method might throw whereas throw keyword is used to disrupt the flow of program and handing over the exception object to run-time to handle it.
    Read more at Difference Between Throw and Throws in Java

    10. What is the difference between an exception and error?

    An exception is an event that represents a condition from which is possible to recover, whereas error represents an external situation usually impossible to recover from.

    All errors thrown by the JVM are instances of Error or one of its subclasses, the more common ones include but are not limited to:
    • OutOfMemoryError – thrown when the JVM cannot allocate more objects because it is out memory, and the garbage collector was unable to make more available
    • StackOverflowError – occurs when the stack space for a thread has run out, typically because an application recurses too deeply
    • ExceptionInInitializerError – signals that an unexpected exception occurred during the evaluation of a static initializer
    • NoClassDefFoundError – is thrown when the classloader tries to load the definition of a class and couldn’t find it, usually because the required class files were not found in the classpath
    • UnsupportedClassVersionError – occurs when the JVM attempts to read a class file and determines that the version in the file is not supported, normally because the file was generated with a newer version of Java
    Although an error can be handled with a try statement, this is not a recommended practice since there is no guarantee that the program will be able to do anything reliably after the error was thrown.
    Read more at Exceptions Hierarchy in Java

    11. What is OutOfMemoryError in Java?

    OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and it’s thrown by JVM when it ran out of heap memory.
    The figure below illustrates the class hierarchy of Error Class.
    We can fix this error by providing more memory to run the java application through java options.
    $>java MyProgram -Xms1024m -Xmx1024m -XX:PermSize=64M -XX:MaxPermSize=256m

    12. What is Chained Exceptions in Java?

    The chained exception feature allows you to associate another exception with an exception. This second exception describes the cause of the first exception.

    For example, imagine a situation in which a method throws an ArithmeticException because of an attempt to divide by zero. However, the actual cause of the problem was that an I/O error occurred, which caused the divisor to be set improperly. Although the method must certainly throw an ArithmeticException, since that is the error that occurred, you might also want to let the calling code know that the underlying cause was an I/O error. Chained exceptions let you handle this, and any other situation in which layers of exceptions exist. This concept was introduced in JDK 1.4.

    Read more about chained exception feature at Java Chained Exceptions with Example

    13. How to write a custom exception in Java?

    In bigger applications, most of the cases we need custom exceptions for representing business exceptions which are, at a level higher than technical exceptions defined by JDK. 
    Here are the steps create a custom exception:
    • Create a new class whose name should end with Exception like ClassNameException. This is a convention to differentiate an exception class from regular ones.
    • Make the class extends one of the exceptions which are subtypes of the java.lang.Exception class. Generally, a custom exception class always extends directly from the Exception class.
    • Create a constructor with a String parameter which is the detail message of the exception. In this constructor, simply call the super constructor and pass the message. In Java, there are two types of exceptions – checked and unchecked exception.
    A simple example of custom exception is shown below.
    public class ResourceNotFoundException extends Exception {
        private static final long serialVersionUID = 1L;
    
        public ResourceNotFoundException(Object resourId) {
            super(resourId != null ? resourId.toString() : null);
        }
    }
    Read more in detail at Guide to Create Custom Exceptions

    14. What is the difference between final, finally and finalize in Java?

    1. final: is used to apply restrictions on class, method, and variable. A final class can't be inherited, final method can't be overridden and final variable value can't be changed.

    2. finally: keyword is used with a try-catch block to provide statements that will always get executed even if some exception arises, usually finally is used to close resources.
    3. finalize: is used to perform clean up processing just before an object is garbage collected.

    15. What happens when an exception is thrown by the main method?

    When an exception is thrown by main() method, Java Runtime terminates the program and print the exception message and stack trace in system console.

    16. What is a try-with-resources statement?

    In Java, the try-with-resources statement is a try statement that declares one or more resources. The resource is as an object that must be closed after finishing the program. The try-with-resources statement ensures that each resource is closed at the end of the statement execution.
    For example:
    public class BufferedReaderExample {
        public static void main(String[] args) {
            try (FileReader fr = new FileReader("C:/workspace/java-io-guide/sample.txt"); BufferedReader br = new BufferedReader(fr);) {
                String sCurrentLine;
    
                while ((sCurrentLine = br.readLine()) != null) {
                    System.out.println(sCurrentLine);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    Read more about the try-with-resource statement at The try-with-resources Statement with Examples

    17. What is a stacktrace and how does it relate to an exception?

    A stack trace provides the names of the classes and methods that were called, from the start of the application to the point an exception occurred.

    It’s a very useful debugging tool since it enables us to determine exactly where the exception was thrown in the application and the original causes that led to it.

    18. What are the Advantages of Java Exceptions?

    Following are advantages of using exceptions in your programs.
    Advantage 1: Separating Error-Handling Code from "Regular" Code
    Advantage 2: Propagating Errors Up the Call Stack
    Advantage 3: Grouping and Differentiating Error Types
    Read more detail about each advantage at Advantages of Java Exceptions with Examples

    19. Can you throw any exception inside a lambda expression’s body?

    When using a standard functional interface already provided by Java, you can only throw unchecked exceptions because standard functional interfaces do not have a “throws” clause in method signatures:
    List<Integer> integers = Arrays.asList(3, 9, 7, 0, 10, 20);
    integers.forEach(i -> {
        if (i == 0) {
            throw new IllegalArgumentException("Zero not allowed");
        }
        System.out.println(Math.PI / i);
    });
    However, if you are using a custom functional interface, throwing checked exceptions is possible:
    @FunctionalInterface
    public static interface CheckedFunction<T> {
        void apply(T t) throws Exception;
    }
    public void processTasks(
      List<Task> taks, CheckedFunction<Task> checkedFunction) {
        for (Task task : taks) {
            try {
                checkedFunction.apply(task);
            } catch (Exception e) {
                // ...
            }
        }
    }
     
    processTasks(taskList, t -> {
        // ...
        throw new Exception("Something happened");
    });

    20. What are the rules we need to follow when overriding a method that throws an exception?

    Several rules dictate how exceptions must be declared in the context of inheritance.
    When the parent class method doesn’t throw any exceptions, the child class method can’t throw any checked exception, but it may throw any unchecked.
    Here’s an example code to demonstrate this:
    class Parent {
        void doSomething() {
            // ...
        }
    }
     
    class Child extends Parent {
        void doSomething() throws IllegalArgumentException {
            // ...
        }
    }
    The next example will fail to compile since the overriding method throws a checked exception not declared in the overridden method:
    class Parent {
        void doSomething() {
            // ...
        }
    }
     
    class Child extends Parent {
        void doSomething() throws IOException {
            // Compilation error
        }
    }
    When the parent class method throws one or more checked exceptions, the child class method can throw any unchecked exception; all, none or a subset of the declared checked exceptions, and even a greater number of these as long as they have the same scope or narrower.
    Here’s an example code that successfully follows the previous rule:
    class Parent {
        void doSomething() throws IOException, ParseException {
            // ...
        }
     
        void doSomethingElse() throws IOException {
            // ...
        }
    }
     
    class Child extends Parent {
        void doSomething() throws IOException {
            // ...
        }
     
        void doSomethingElse() throws FileNotFoundException, EOFException {
            // ...
        }
    }
    Note that both methods respect the rule. The first throws fewer exceptions than the overridden method, and the second, even though it throws more; they’re narrower in scope.
    However, if we try to throw a checked exception that the parent class method doesn’t declare or we throw one with a broader scope; we’ll get a compilation error:
    class Parent {
        void doSomething() throws FileNotFoundException {
            // ...
        }
    }
     
    class Child extends Parent {
        void doSomething() throws IOException {
            // Compilation error
        }
    }
    When the parent class method has a throws clause with an unchecked exception, the child class method can throw none or any number of unchecked exceptions, even though they are not related.
    Here’s an example that honors the rule:
    class Parent {
        void doSomething() throws IllegalArgumentException {
            // ...
        }
    }
     
    class Child extends Parent {
        void doSomething()
          throws ArithmeticException, BufferOverflowException {
            // ...
        }
    }

    21. Java Exception Handling Best Practices

    1. Clean up Resources in a Finally Block or Use a Try-With-Resource Statement
    2. Throw Specific Exception
    3. Do not catch the Exception class rather catch specific subclasses
    4. Never catch a Throwable class
    5. Always correctly wrap the exceptions in custom exceptions so that stack trace is not lost
    6. Catch the most specific exception first
    7. Don’t ignore exceptions rather log the exceptions
    8. Never throw any exception from finally block
    9. Don’t use printStackTrace() statement or similar methods
    10. Use finally blocks instead of catch blocks if you are not going to handle the exception
    11. Validate user input to catch adverse conditions very early in the request processing
    12. Throw Exceptions With Descriptive Messages
    Learn each exception handling best practice with examples of Java Exception Handling Best Practices

    Related Java Interview Articles

    Comments