Practice commonly asked
Exception Handling interview questions with clear answers and explanations.
30
Interview Questions
Questions & Answers
Exception Handling Interview Questions
30 Questions
Q 91
What is RuntimeException?
Easy
Answer
RuntimeException is the superclass of unchecked exceptions that normally indicate programming errors, invalid arguments, or invalid state.
Explanation
The compiler does not require RuntimeException subclasses to be caught or declared with throws. Common examples include NullPointerException and IllegalArgumentException.
Code Example
Java
static void setLimit(int limit) {
if (limit < 0) {
throw new IllegalArgumentException(
"Limit cannot be negative"
);
}
}
Reference:
Java Exception Handling
Q 92
What is the exception hierarchy in Java?
Easy
Answer
Throwable is the root type, with Exception and Error as its two major branches.
Explanation
RuntimeException is a subclass of Exception. The hierarchy allows catch blocks to handle exceptions at different levels of specificity.
OutOfMemoryError occurs when the JVM cannot allocate required memory for an operation.
Explanation
It indicates a serious memory problem and is not normally treated like a recoverable application exception. The underlying memory usage or JVM configuration should be investigated.
Code Example
Java
List<byte[]> data = new ArrayList<>();
while (true) {
data.add(new byte[1024 * 1024]);
}
// Eventually the JVM may throw OutOfMemoryError.
Reference:
Java Exception Handling
Q 94
What is StackOverflowError?
Medium
Answer
StackOverflowError occurs when a thread's stack cannot accommodate further method calls, commonly because of excessive or infinite recursion.
Explanation
It is an Error rather than an Exception. The correct solution is normally to fix the recursion or algorithm rather than catch the error as normal business logic.
Usually no. Application code should generally not catch Error because it represents serious conditions such as JVM resource exhaustion or linkage failures.
Explanation
Catching Error indiscriminately can leave the application in an unsafe state. Only specialized infrastructure or recovery mechanisms may have a legitimate reason to handle particular Error types.
What is the difference between Error and Exception?
Medium
Answer
Exception represents conditions applications may often handle, while Error represents serious JVM or system-level problems that applications generally should not try to recover from.
Explanation
Both extend Throwable, but they have different intended meanings. Examples include IOException as an Exception and OutOfMemoryError as an Error.
Code Example
Java
try {
Files.readString(Path.of("data.txt"));
} catch (IOException e) {
System.out.println("Recoverable I/O problem");
}
// Do not normally catch OutOfMemoryError as normal application flow.
Reference:
Java Exception Handling
Q 97
Can finally be skipped in Java?
Medium
Answer
Normally finally executes, but it may not execute if the JVM terminates before reaching it, such as through System.exit().
Explanation
The important distinction is that finally is reliable for normal control-flow completion and exception propagation, but it is not an absolute guarantee against JVM termination or external process termination.
What happens if both try and finally contain return statements?
Medium
Answer
A return from finally can override a return from the try block.
Explanation
Although Java permits it, returning from finally is strongly discouraged because it can hide the original return value and can also suppress an exception thrown from the try block.
Yes. A finally block can throw an exception, but doing so can replace an exception that was already being propagated.
Explanation
This is one reason cleanup code should be written carefully. If the try block fails and finally throws another exception, the original failure can become harder to observe. Resource management is generally safer with try-with-resources.
Code Example
Java
try {
throw new IOException("File processing failed");
} finally {
throw new RuntimeException("Cleanup failed");
}
Reference:
Java Exception Handling
Q 100
What happens if an exception is thrown inside a catch block?
Medium
Answer
If a catch block throws another exception and does not handle it itself, the new exception propagates to the caller.
Explanation
The original exception has already entered the catch handler. If the handler itself fails, the newly thrown exception becomes the active failure unless the code explicitly preserves the original exception as its cause.
Can we catch multiple exception types in one catch block?
Easy
Answer
Yes. Java supports multi-catch using the | operator when the same handling logic applies to multiple exception types.
Explanation
Multi-catch reduces duplicate handling code. The exception types must be alternatives rather than a parent-child relationship, because one type cannot be a subtype of another in the same multi-catch declaration.
Why must a subclass exception catch block come before its superclass?
Medium
Answer
A subclass catch block must come before its superclass because the superclass would also catch the subclass exception, making the later catch unreachable.
Explanation
For example, FileNotFoundException is a subclass of IOException. If IOException is caught first, a later FileNotFoundException handler could never be reached, so the compiler reports an unreachable catch block.
Yes. A try block can have multiple catch blocks so different exception types can be handled differently.
Explanation
Multiple catch blocks are useful when different failures require different actions. Java checks the catch blocks from top to bottom and selects the first compatible handler. Therefore, more specific exception types should normally appear before their broader parent types.
Fail-fast handling detects an invalid condition as early as possible and stops processing rather than continuing with an unsafe or invalid state.
Explanation
Fail-fast behavior is useful when continuing would make the system state less reliable or produce misleading results. The key is to validate important preconditions early and reject invalid input before expensive or state-changing operations begin.
Code Example
Java
static void register(Student student) {
if (student == null) {
throw new IllegalArgumentException(
"Student is required"
);
}
saveStudent(student);
}
Reference:
Java Exception Handling
Q 105
What is exception translation?
Hard
Answer
Exception translation converts a lower-level technical exception into an exception that is meaningful to the layer or domain handling it.
Explanation
For example, a repository may receive SQLException, but a service layer may not want to expose database-specific details to its callers. It can translate the exception into a domain or service exception while preserving the original cause.
Code Example
Java
try {
questionRepository.save(question);
} catch (SQLException e) {
throw new QuestionPersistenceException(
"Unable to save question\
}
Reference:
\n e\n );\n}""}"
Q 106
What is exception rethrowing?
Medium
Answer
Rethrowing means catching an exception and throwing it again so that a higher layer can handle it.
Explanation
A method may catch an exception temporarily to add logging, cleanup, metrics, or context, and then rethrow it. The important point is that the exception is not silently swallowed when the current layer cannot actually recover from it.
IllegalStateException indicates that a method was called when the object or application was in an inappropriate state for that operation.
Explanation
Unlike IllegalArgumentException, the problem is not necessarily the method argument. The object may be valid, but its current state does not permit the requested operation. For example, submitting an exam before it has started is an invalid state.
Code Example
Java
class Exam {
private boolean started;
void submit() {
if (!started) {
throw new IllegalStateException(
"Exam has not started"
);
}
System.out.println("Exam submitted");
}
}
Reference:
Java Exception Handling
Q 108
What is IllegalArgumentException?
Easy
Answer
IllegalArgumentException indicates that a method received an argument that is inappropriate or invalid for the method's contract.
Explanation
The problem is with the value supplied to the method, not necessarily with the current state of the object. It is commonly used for validating ranges, required values, or other method-input rules.
Code Example
Java
static void setPassingMark(int mark) {
if (mark < 0 || mark > 100) {
throw new IllegalArgumentException(
"Mark must be between 0 and 100"
);
}
}
Reference:
Java Exception Handling
Q 109
What is NullPointerException and how can it be prevented?
Easy
Answer
NullPointerException occurs when code attempts an operation that requires an object reference but the reference is null.
Explanation
It commonly occurs when calling an instance method, accessing an instance field, or dereferencing a null reference. Prevention includes validating inputs, maintaining clear object invariants, using Optional where appropriate, and using Java's null-safe APIs instead of blindly dereferencing values.
Code Example
Java
Student student = findStudent(studentId);
if (student == null) {
System.out.println("Student not found");
return;
}
System.out.println(student.getName());
Reference:
Java Exception Handling
Q 110
What is the difference between final, finally, and finalize?
Medium
Answer
final is a Java keyword, finally is an exception-handling block, and finalize was a legacy object-cleanup method that has been deprecated for removal.
Explanation
final is used to restrict reassignment, inheritance, or overriding depending on where it is used. finally is associated with exception handling and cleanup. finalize was associated with garbage collection but is not a reliable resource-management mechanism and should not be used in modern Java code.
Code Example
Java
final int maxAttempts = 3;
try {
login();
} finally {
releaseResources();
}
// Do not use finalize() for resource cleanup.
Reference:
Java Exception Handling
Q 111
What is a suppressed exception?
Hard
Answer
A suppressed exception is an exception that occurs while an earlier exception is already being handled, commonly during resource closing in try-with-resources.
Explanation
In try-with-resources, the exception from the main operation is normally treated as the primary exception. If closing the resource also throws an exception, Java attaches that closing exception as suppressed. This preserves both failures instead of losing one of them.
Code Example
Java
class Resource implements AutoCloseable {
public void close() throws Exception {
throw new Exception("Closing failed");
}
}
try (Resource resource = new Resource()) {
throw new Exception("Main operation failed");
} catch (Exception e) {
System.out.println("Primary: " + e.getMessage());
for (Throwable suppressed : e.getSuppressed()) {
System.out.println(
"Suppressed: " + suppressed.getMessage()
);
}
}
Reference:
Java Exception Handling
Q 112
What is try-with-resources?
Easy
Answer
Try-with-resources automatically closes resources that implement AutoCloseable after the try block finishes.
Explanation
Try-with-resources is preferred for files, streams, database resources, and similar closeable objects. Java closes the resources automatically even when the main operation throws an exception, which reduces resource-leak risks.
Why should we avoid catching Exception everywhere?
Medium
Answer
Catching Exception everywhere can hide programming errors, make failures difficult to diagnose, and prevent appropriate recovery at higher layers.
Explanation
A broad catch is sometimes appropriate at an application boundary for logging or converting failures into a response, but it is usually a poor choice inside every method. Catch the most specific exception that the current layer can actually handle.
Code Example
Java
try {
paymentService.charge(order);
} catch (PaymentDeclinedException e) {
// This layer understands how to handle this condition.
showPaymentFailure();
}
Reference:
Java Exception Handling
Q 114
What is exception chaining?
Medium
Answer
Exception chaining preserves the original exception as the cause of a new exception.
Explanation
Exception chaining is useful when a lower layer throws a technical exception but a higher layer needs to expose a more meaningful application-level exception. The original cause should be retained so debugging information is not lost.
Code Example
Java
try {
userRepository.save(user);
} catch (SQLException e) {
throw new UserServiceException(
"Unable to save user\
}
Reference:
\n e\n );\n}""}"
Q 115
What is a custom exception and when should you create one?
Medium
Answer
A custom exception is an application-specific exception type created when a meaningful domain or technical failure needs its own identity.
Explanation
Custom exceptions are useful when the caller needs to distinguish a particular business condition from other failures. For example, an exam application may need to distinguish an already-submitted exam from a database failure. A custom exception should represent a meaningful condition rather than simply increasing the number of exception classes.
Code Example
Java
class ExamAlreadySubmittedException extends RuntimeException {
ExamAlreadySubmittedException(String message) {
super(message);
}
}
if (exam.isSubmitted()) {
throw new ExamAlreadySubmittedException(
"This exam has already been submitted"
);
}
Reference:
Java Exception Handling
Q 116
What happens when a constructor throws an exception?
Medium
Answer
The object is not successfully constructed, so the constructor call does not produce a usable object reference.
Explanation
A constructor can reject invalid input or invalid initial state by throwing an exception. The caller receives the exception instead of a successfully constructed object. This is useful for preventing invalid objects from entering the application.
Code Example
Java
class Student {
Student(String name) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("Student name is required");
}
}
}
try {
Student student = new Student(null);
} catch (IllegalArgumentException e) {
System.out.println("Student creation failed");
}
Reference:
Java Exception Handling
Q 117
What is exception propagation?
Medium
Answer
Exception propagation is the movement of an unhandled exception from the current method to its caller and potentially further up the call stack.
Explanation
A lower-level method does not always have enough context to recover from a failure. In that situation it can allow the exception to propagate. A higher layer, such as a service or controller, can then decide how the failure should be handled.
throw explicitly throws an exception object, while throws declares that a method may propagate specified exceptions to its caller.
Explanation
Use throw when the method detects a condition that should immediately become an exception. Use throws in the method signature to tell callers that the method may propagate particular exceptions, especially checked exceptions.
Code Example
Java
static void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older");
}
}
static String readConfig() throws IOException {
return Files.readString(Path.of("config.properties"));
}
Reference:
Java Exception Handling
Q 119
What is the purpose of finally?
Easy
Answer
finally is used for cleanup code that should normally execute whether an exception occurs or not.
Explanation
finally is commonly used when a resource or state must be cleaned up after an operation. For closeable resources, try-with-resources is usually preferable because it handles resource closing automatically and more safely.
A catch block handles an exception thrown from its associated try block.
Explanation
A catch block should normally handle a specific failure that the current layer understands. It can recover, return a meaningful response, log the failure, or translate the exception into a more appropriate application-level exception.
Code Example
Java
try {
int mark = Integer.parseInt(input);
System.out.println(mark);
} catch (NumberFormatException e) {
System.out.println("Mark must be a number");
}
Reference:
Java Exception Handling
About This Topic
Prepare for
Exception Handling interviews with important concepts
and commonly asked questions.