In the article, we will discuss some of the most commonly Java Exception Handling Interview Questions.
Basic Level : Java Exception Handling Interview Questions
Let’s first discuss Basic level Java Exception Handling Interview Questions.
What is Exception Hierarchy ?
In Exception hierarchy, Throwable
is at the root, with Error
and Exception
as its immediate subclasses. Exception
is further divided into checked and unchecked exceptions.
Read More: Exception Handling in Java: Comprehensive Guide
What is Throwable?
In Java, Throwable
is the root class for all exceptions and errors. It’s a fundamental class in the exception hierarchy that allows you to catch and handle various exceptional conditions that might occur during program execution. Both exceptions and errors in Java are subclasses of the Throwable
class.
Read More: Exception Handling in Java: Comprehensive Guide
What is the difference between Exception vs Error?
Aspect | Exception | Error |
---|---|---|
Hierarchy | Subclass of Throwable | Also a subclass of Throwable |
Handling | Expected to be caught and handled by code | Usually not caught or handled by normal code |
Examples | IOException , NullPointerException | OutOfMemoryError , StackOverflowError |
Checked/Unchecked | Can be checked or unchecked | Unchecked (subclasses of RuntimeException ) |
Cause | Generally caused by issues in application | Often caused by serious system or JVM problems |
Recoverable | Often recoverable with proper handling | Typically not recoverable, indicates critical issues |
Action | Requires explicit handling (try-catch) | Usually not explicitly handled in code |
What are the differences between Checked and UnChecked Exception ?
This is the most frequently asked Java Exception Handling Interview Questions.
Aspect | Checked Exception | Unchecked Exception |
---|---|---|
Handling | Must be caught or declared using throws | Optional to catch or declare |
Examples | IOException , SQLException | NullPointerException , IllegalArgumentException |
Inheritance | Subclass of Exception | Subclass of RuntimeException |
Caused By | Usually caused by external factors or input validation | Often caused by issues within the code |
Recovery | Often recoverable with proper handling | May or may not be recoverable |
Compile-Time Check | Compiler enforces handling or declaration | No compile-time enforcement |
Action | Encourages explicit handling in code | Handling is not mandatory in code |
Read More : Difference between Checked and Unchecked Exception in Java
How to create Custom Exceptions ?
Creating custom exceptions in Java involves extending existing exception classes (like Exception
or its subclasses) to define specialized exception types.
Read More : Custom Exception in Java
throw vs throws
Please read throw and throws
try, catch, and finally
Please read try, catch, and finally
List of Common Checked Exceptions
Please read Common Checked Exceptions
List of Common Unchecked Exceptions
Please read Common Unchecked Exceptions
List of Common Errors
Please read Common Errors
What do you understand by Exception Propagation?
Exception Propagation refers to the process in which an exception, thrown in a method, is propagated or passed to its caller method or the calling code. If an exception is not caught and handled within a method, it’s propagated up the call stack to the methods that invoked the current method. This continues until the exception is caught and handled, or until it reaches the top-level method (such as the main
method), where unhandled exceptions might result in the termination of the program.
Read More Exception Propagation
Can you catch multiple exceptions in a single catch block?
Yes, you can catch multiple exceptions using a single catch block by separating the exception classes with the pipe |
symbol.
public class MultiExceptionExample {
public static void main(String[] args) {
try {
int[] numbers = { 1, 2, 3 };
System.out.println(numbers[5]); // This will throw an ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
System.out.println("Caught exception: " + e.getClass().getSimpleName());
}
}
}
Advanced Level : Java Exception Handling Interview Questions
Now, let’s discuss Advanced level Java Exception Handling Interview Questions.
ClassNotFoundException vs NoClassDefFoundError
Please Read ClassNotFoundException vs NoClassDefFoundError
What is the purpose of try-with-resources statement?
The try-with-resources
statement is a feature introduced in Java 7 that simplifies resource management by automatically closing resources that implement the AutoCloseable
or java.io.Closeable
interface. It ensures that resources are properly closed, whether the code within the try
block completes normally or an exception is thrown.
The syntax of the try-with-resources
statement is as follows:
try (ResourceType resource1 = new ResourceType();
ResourceType resource2 = new ResourceType()) {
// Code that uses the resources
} catch (ExceptionType e) {
// Exception handling
}
In this structure:
- You declare and initialize the resources you want to use inside the parentheses after the
try
keyword. - The resources are automatically closed when the
try
block is exited, regardless of whether the block is exited normally or due to an exception. - The resources are effectively final, meaning they cannot be reassigned within the block.
- You can catch and handle exceptions that might be thrown during the use of resources.
Read More : Try with Resources
What is Exception Chaining?
Exception chaining allows you to associate one exception with another, providing more detailed information about the cause of the exception. It was introduced in Java 7 and can be helpful in diagnosing and debugging issues.
Here’s an example:
public class ExceptionChainingExample {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
throw new RuntimeException("An error occurred while performing the division.", e);
}
}
public static int divide(int dividend, int divisor) {
return dividend / divisor;
}
}
In this example, when a division by zero occurs in the divide
method, an ArithmeticException
is thrown. In the catch
block, we’re throwing a RuntimeException
while chaining the original ArithmeticException
as the cause. This way, the information about the original exception is preserved, aiding in better error diagnosis.
What is the purpose of the getSuppressed() method in Java exceptions?
The getSuppressed()
method in Java exceptions is used to retrieve an array of suppressed exceptions that were added to the current exception using the addSuppressed()
method. This is particularly useful when handling exceptions that might occur during resource cleanup, such as in a try-with-resources
statement.
Here’s an example:
public class SuppressedExceptionsExample {
public static void main(String[] args) {
try (ResourceA a = new ResourceA(); ResourceB b = new ResourceB()) {
throw new Exception("Primary Exception");
} catch (Exception e) {
Throwable[] suppressed = e.getSuppressed();
for (Throwable suppressedException : suppressed) {
System.out.println("Suppressed: " + suppressedException.getMessage());
}
}
}
}
class ResourceA implements AutoCloseable {
@Override
public void close() throws Exception {
throw new Exception("Exception in ResourceA");
}
}
class ResourceB implements AutoCloseable {
@Override
public void close() throws Exception {
throw new Exception("Exception in ResourceB");
}
}
In this example, the SuppressedExceptionsExample
demonstrates how suppressed exceptions can be accessed using the getSuppressed()
method. The ResourceA
and ResourceB
classes simulate resources with exceptions during their closure. When an exception is thrown in the try
block, the suppressed exceptions from both resources are collected and printed within the catch
block.
Conclusion: Java Exception Handling Interview Questions with Answers
In this article, we explored a wide range of Java Exception Handling Interview Questions, addressing both basic and advanced-level concepts.
Java Exceptions Must-Read Articles: