Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Exceptions Handling Interview Questions and Answers

DZone 's Guide to

Java Exceptions Handling Interview Questions and Answers

Let's take a look at key these Java exceptions handling questions and answers that are important for any Java developer preparing for an interview.

· Java Zone ·
Free Resource

In this article, we will discuss 21 important Java exception handling interview questions with the answers.

Before we get started, check out this  complete beginner-to-expert, in-depth exception handling tutorial in Java!

Let's explore the following questions, which are likely to appear in technical interviews for Java developers regarding exceptions.

  1. What is an exception in Java?
  2. How does exception handling work in Java?
  3. What are 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 the 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 throw and throws keyword in Java?
  10. What is the difference between an exception and error?
  11. What is the OutOfMemoryError in Java?
  12. What are chained exceptions in Java?
  13. How do you write a custom exception 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 stacktrace 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 that we need to follow when overriding a method that throws an exception?
  21. What are some of the exception handling best practices?

1. What Is an Exception in Java?

An exception is an event that occurs during the execution of a program and disrupts the normal flow of the program's instructions.

Read more about exceptions in Java in the Java Exception Handling Guide!

2. How Does Exception Handling Work in Java?

Below steps demonstrates how the 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.









Read more at How the Exception Handling Works in Java with Example.

3. What Are  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. catch: The Java catch block is used to handle the exception. It must be used after the try block only. You can use multiple catch blocks with a singletry.

3. throw: Sometimes, we explicitly want to create an exception object and then throw it to halt the normal processing of the program. The 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 the throws keyword in the method signature to let the caller program know that the exceptions might be thrown by the method. The caller method might handle these exceptions or propagate it to its caller method using the throws keyword. We can provide multiple exceptions in the throws clause and it can be used with the main()method also.

5. finally: The finally block is optional and can be used only with thetry-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. The finally block gets executed always, whether an exception occurs or not.

This diagram provides a summary of the 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?

Thethrows 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 {
    // ...
}


Thethrow 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 the throws and throw keywords here: Java throw Keyword with ExampleJava throws Keyword with Example.

5. How Can You Handle an Exception?

You can handle an exception by using a try-catch-finallystatement:

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 inside it or not.

Read more about how to handle exceptions here: Java Exception Handling Tutorial.

6. Explain the Java Exception Hierarchy. 

The objects that inherit from the Throwable class that includes 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,  OutOfMemoryErrorUnKnownError,  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, when dealing with the FileNotFoundException, we should catch this exception and provide a useful message to the user and log it properly for debugging purposes. The exception is the parent class of all checked exceptions.

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

Read more about the exception hierarchy in Java here: Exceptions Hierarchy in Java.

7. How Can you Catch Multiple Exceptions?

There are three ways to handle 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 Exceptions in Java?

1. Checked exceptions should be handled in the code using a try-catch block, or else, the method should use the 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 thethrows clause of the method.

2. The exception is the superclass of all checked exceptions, whereas RuntimeException is the superclass of all unchecked exceptions. Note that RuntimeException is the child class ofException.

3. Checked exceptions are error scenarios that require being handled in the code, or else, you will get a compile-time error. For example, if you use FileReader to read a file, it throws the 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, the NullPointerException when invoking a method on an object reference without making sure that it’s not null. I can write a method to remove all the vowels from the string. It’s the caller's 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 Keywords in Java?

The throws keyword is used with a method signature to declare exceptions that the method might throw, whereas the throw keyword is used to disrupt the flow of a 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 an Error?

An exception is an event that represents a condition from which it is possible to recover, whereas an 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:

  •  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. This is 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 on this subject here: Exceptions Hierarchy in Java.

11. What Is the OutOfMemoryError in Java?

The OutOfMemoryError in Java is a subclass of the java.lang. VirtualMachineError and it’s thrown by the JVM when it runs out of heap memory.

The figure below illustrates the class hierarchy of the 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 a Chained Exception 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 where 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 ArithmeticExceptionsince 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 here: Java Chained Exceptions with Example.

13. How Can We Write a Custom Exception in Java?

In bigger applications, most of the cases we need custom exceptions for representing business exceptions are at a level higher than technical exceptions defined by the JDK.

Here are the steps that create a custom exception:

  • Create a new class whose name should end with an Exception, like the ClassNameException. This is a convention to differentiate an exception class from regular ones.
  • Make the class extends one of the exceptions that 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 exceptions.

A simple example of a 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 the class, method, and variable. The finalclass can't be inherited — nor can it be overridden or changed.

2. finally: this keyword is used with the 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 the 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 prints the exception message and the stack trace in-system console.

16. What Is the Try-With-Resources Statement?

In Java, the try-with-resourcesstatement 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 here: 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 that 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?

The following are advantages of using exceptions in your programs:

1. Separating Error-handling code from "regular" code

2: Propagating errors up the call stack

3: Grouping and differentiating error types

Read more detail about each advantage here 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 its 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 exceptions, 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, including all, none, or a subset of the declared checked exceptions and an 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 theparentclass method has a throws clause with an unchecked exception, the childclass method can throw none or any number of unchecked exceptions, even though they are not related. Here’s an example that honors that 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-resources statement
  2. Throw a 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 the 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 the  finally block
  9. Don’t use the printStackTrace() statement or similar methods
  10. Use the 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 practices with examples on Java Exception Handling Best Practices

I kindly suggest that if you have other interview questions regarding Java exception handling that will help others prepare for their interview, leave a note in the comments below!

References

Java Exception Handling Tutorial

Java Exception Interview Questions and Answers - JournalDev

Java Exceptions Interview Questions (+ Answers) - Baeldung

Topics:
java ,exceptions ,questions answers ,developers ,code ,checked exceptions ,unchecked

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}