Interview Help Desk Exception Handling

Exception Handling

Practice commonly asked Exception Handling interview questions with clear answers and explanations.

30 Interview Questions

Exception Handling Interview Questions

30 Questions
Q 1

What is the 'Fail-Fast' vs 'Fail-Safe' iterator behavior with exceptions?

Medium
Answer
Fail-Fast iterators throw ConcurrentModificationException immediately upon detecting structural modifications during iteration. Fail-Safe iterators operate on clone/snapshot copies and do not throw exceptions when collection changes during iteration.
Explanation
Standard collections (ArrayList, HashMap) use fail-fast iterators via internal modCount checks. Concurrent collections (CopyOnWriteArrayList, ConcurrentHashMap) use fail-safe/weakly-consistent iterators.
Code Example Java
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();\
map.put("A\
Reference: 1);\\nmap.put(\""B\""
Q 2

How does exception handling work inside CompletableFuture / Asynchronous pipelines?

Hard
Answer
In CompletableFuture asynchronous pipelines, exception handling is achieved using operators like exceptionally(), handle(), or whenComplete().
Explanation
In async pipelines, exceptions are captured inside the CompletableFuture object and passed down the dependency graph rather than bubbling up call stacks.
Code Example Java
CompletableFuture.supplyAsync(() -> {\
    if (true) throw new RuntimeException("Async task failed");\
    return "Success";\
}).exceptionally(ex -> {\
    System.err.println("Handled async failure: " + ex.getMessage());\
    return "Fallback Value";\
}).thenAccept(System.out.println);
Reference: Java Exception Handling
Q 3

What is NoClassDefFoundError vs ClassNotFoundException?

Hard
Answer
ClassNotFoundException is a checked exception thrown when explicit class loading (Class.forName) fails to locate a class on the classpath. NoClassDefFoundError is an Error thrown when a class present at compile-time is missing at runtime during dynamic linkage.
Explanation
NoClassDefFoundError often happens due to missing dependent JAR files at deployment or static initializers failing when the class was loaded.
Code Example Java
try {\
    Class<?> clazz = Class.forName("com.missing.Driver");\
} catch (ClassNotFoundException e) {\
    System.out.println("Class not found on classpath: " + e.getMessage());\
}
Reference: Java Exception Handling
Q 4

Best practices for logging exceptions in Java applications?

Medium
Answer
Log exceptions with sufficient context and full stack trace using logging frameworks (SLF4J/Logback). Never swallow exceptions silently or log and rethrow the same exception.
Explanation
Do not 'log and throw' as it leads to duplicate log entries. Either catch and handle/log, or translate and rethrow with context.
Code Example Java
// GOOD practice:\
try {\
    service.execute();\
} catch (DataAccessException e) {\
    logger.error("Failed to process operation for user: {}\
}
Reference: userId
Q 5

What is StackOverflowError vs OutOfMemoryError?

Medium
Answer
StackOverflowError occurs when thread call stack depth exceeds JVM limits (usually due to infinite recursion). OutOfMemoryError occurs when JVM heap space is exhausted and garbage collection cannot reclaim memory.
Explanation
Both are subclasses of VirtualMachineError (under Error). They reflect low-level JVM resource exhaustion rather than regular application exception states.
Code Example Java
// StackOverflowError example:
void recursive() {
    recursive();
}

// OutOfMemoryError example:
void fillHeap() {
    List<byte[]> memory = new ArrayList<>();
    while(true) memory.add(new byte[10_000_000]);
}
Reference: Java Exception Handling
Q 6

What is ConcurrentModificationException and how do you handle it?

Medium
Answer
ConcurrentModificationException occurs when a collection is modified structurally while iterating over it using illegal methods (e.g., adding/removing directly via List rather than Iterator).
Explanation
To safely modify a collection during iteration, use Iterator.remove(), removeIf(), or thread-safe concurrent collections like CopyOnWriteArrayList.
Code Example Java
List<String> list = new ArrayList<>(List.of("A\
Reference: \""B\""
Q 7

What is ClassCastException and how do you prevent it?

Easy
Answer
ClassCastException is an unchecked exception thrown when code attempts to cast an object to a subclass of which it is not an instance.
Explanation
ClassCastException can be avoided using instanceof checks or Pattern Matching for instanceof (Java 16+).
Code Example Java
Object obj = "Hello Java";\
// Safe casting using pattern matching\
if (obj instanceof String s) {\
    System.out.println(s.toUpperCase());\
} else {\
    System.out.println("Not a String");\
}
Reference: Java Exception Handling
Q 8

What is Rethrowing Exception and Precise Rethrow in Java?

Hard
Answer
Precise rethrow (Java 7+) allows rethrowing an exception caught via a generic Exception parameter while the compiler tracks the exact checked exceptions declared in the try block.
Explanation
When rethrowing an exception caught as Exception, if the variable is effectively final, Java checks the actual checked exception types thrown in try, allowing narrow throws declarations on the method.
Code Example Java
public void process() throws IOException, SQLException {\
    try {\
        if (Math.random() > 0.5) throw new IOException("IO error");\
        else throw new SQLException("DB error");\
    } catch (Exception e) {\
        // Precise rethrow tracks actual checked exception types\
        throw e;\
    }\
}
Reference: Java Exception Handling
Q 9

How does UncaughtExceptionHandler work in Java threads?

Hard
Answer
UncaughtExceptionHandler is an interface used to handle uncaught exceptions thrown by a thread when execution terminates abnormally due to an unhandled exception.
Explanation
You can set default or thread-specific uncaught exception handlers to log unexpected runtime thread failures gracefully.
Code Example Java
Thread thread = new Thread(() -> {\
    throw new RuntimeException("Unexpected worker crash");\
});\
thread.setUncaughtExceptionHandler((t
Reference: e) -> {\\n System.err.println(\""Thread \"" + t.getName() + \"" died due to: \"" + e.getMessage());\\n});\\nthread.start();""}"
Q 10

What is the order of catch blocks when handling inheritance hierarchies?

Easy
Answer
Catch blocks must be ordered from the most specific subclass exception to the most general superclass exception.
Explanation
If a superclass exception catch block is placed above a subclass catch block, the subclass block becomes unreachable and causes a compilation error.
Code Example Java
try {\
    int data = 10 / 0;\
} catch (ArithmeticException e) { // Specific subclass first\
    System.out.println("Arithmetic failure: " + e.getMessage());\
} catch (Exception e) {            // General superclass last\
    System.out.println("General failure: " + e.getMessage());\
}
Reference: Java Exception Handling
Q 11

What are method overriding rules regarding checked exceptions in Java?

Hard
Answer
An overriding subclass method cannot declare broader or new checked exceptions than those declared by the superclass method, but it can declare fewer, child exceptions, or none.
Explanation
Subclasses can declare fewer checked exceptions or narrower subclasses of declared checked exceptions. Subclasses can declare any unchecked exception regardless of superclass declaration.
Code Example Java
class Parent {
    void process() throws IOException {}
}
class Child extends Parent {
    @Override
    void process() throws FileNotFoundException {} // Valid: narrower checked exception
}
Reference: Java Exception Handling
Q 12

What is IllegalStateException and how does it differ from IllegalArgumentException?

Medium
Answer
IllegalArgumentException indicates invalid method arguments. IllegalStateException indicates that the target object's state is unsuitable for executing the requested operation, regardless of argument values.
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 13

What is the difference between NullPointerException and IllegalArgumentException?

Easy
Answer
NullPointerException is thrown when attempting to invoke a method or access a field on a null object reference. IllegalArgumentException indicates that a method was passed an invalid or inappropriate argument value.
Explanation
Objects.requireNonNull() can be used to fail-fast with NPE when null arguments are received, whereas IllegalArgumentException validates domain logic constraints.
Code Example Java
public void setPercentage(double val) {\
    if (val < 0.0 || val > 100.0) {\
        throw new IllegalArgumentException("Percentage must be between 0 and 100");\
    }\
}
Reference: Java Exception Handling
Q 14

What happens when a method returns from both try and finally blocks?

Medium
Answer
If both try/catch and finally blocks contain return statements, the return statement in the finally block overrides any previous return or thrown exception from try/catch.
Explanation
Returning values or throwing exceptions from inside a finally block is considered an anti-pattern because it silently swallows exceptions thrown in the try block.
Code Example Java
public static int testMethod() {\
    try {\
        throw new RuntimeException("Error");\
    } finally {\
        return 42; // Swallows the RuntimeException and returns 42!\
    }\
}
Reference: Java Exception Handling
Q 15

When does a finally block NOT execute in Java?

Medium
Answer
A finally block will not execute if System.exit() is called, if the JVM crashes/terminates unexpectedly, if the executing thread is killed, or in an infinite loop inside try/catch.
Explanation
System.exit(status) halts the JVM immediately, bypassing any remaining finally blocks.
Code Example Java
try {\
    System.out.println("Executing task");\
    System.exit(0);\
} finally {\
    // This block will NOT be executed!\
    System.out.println("Cleanup code");\
}
Reference: Java Exception Handling
Q 16

What are Suppressed Exceptions in Java?

Hard
Answer
Suppressed exceptions occur when an exception is thrown inside a try block and another exception is thrown while closing auto-closeable resources in try-with-resources. The resource-closing exception is attached as 'suppressed'.
Explanation
The primary exception thrown from the body is preserved, and exceptions thrown while closing resources are appended to it. Suppressed exceptions can be accessed via e.getSuppressed().
Code Example Java
try (BadResource resource = new BadResource()) {\
    throw new RuntimeException("Primary failure");\
} 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 17

What is Exception Chaining (Cause Exception)?

Medium
Answer
Exception chaining allows associating one exception as the root cause of another, preserving low-level diagnostic information while abstracting errors at higher application layers.
Explanation
Exception chaining is implemented by passing the original exception to the constructor of the new exception or using initCause(). The original cause can be retrieved using getCause().
Code Example Java
try {\
    database.connect();\
} catch (SQLException e) {\
    throw new ServiceException("Failed to initialize service layer\
}
Reference: e);\\n}""}"
Q 18

How do you create a custom user-defined exception in Java?

Medium
Answer
A custom exception is created by extending Exception (for checked exceptions) or RuntimeException (for unchecked exceptions) and providing standard constructors.
Explanation
Custom exceptions should provide constructors accepting error messages and cause exceptions to support exception chaining.
Code Example Java
public class OrderNotFoundException extends RuntimeException {
    public OrderNotFoundException(String message) {
        super(message);
    }
    public OrderNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }
}
Reference: Java Exception Handling
Q 19

What is multi-catch in Java and what are its restrictions?

Medium
Answer
Multi-catch (Java 7+) allows multiple disjoint exception types to be caught in a single catch block using the pipe (|) operator.
Explanation
In a multi-catch clause, the exception variable is implicitly final and cannot be reassigned. Also, exceptions in the same multi-catch cannot have a class inheritance relationship (subclass/superclass conflict).
Code Example Java
try {\
    Class<?> clazz = Class.forName("com.example.Service");\
    clazz.getMethod("execute").invoke(null);\
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException e) {\
    System.out.println("Reflective operation failed: " + e.getMessage());\
}
Reference: Java Exception Handling
Q 20

What is the difference between throw and throws keywords?

Easy
Answer
The 'throw' keyword explicitly throws an exception instance from code, whereas 'throws' is a method signature keyword declaring that the method may propagate specified exceptions caller-side.
Explanation
'throw' is followed by an instance (e.g., throw new Exception()), while 'throws' is followed by exception class names (e.g., throws IOException, SQLException).
Code Example Java
void validateBalance(double amount) throws InsufficientBalanceException {\
    if (amount <= 0) {\
        throw new IllegalArgumentException("Amount must be positive");\
    }\
    if (amount > balance) {\
        throw new InsufficientBalanceException("Insufficient funds");\
    }\
}
Reference: Java Exception Handling
Q 21

What is Try-With-Resources and how does AutoCloseable work?

Medium
Answer
Try-With-Resources (introduced in Java 7) automatically closes resources that implement AutoCloseable or Closeable at the end of the statement, eliminating boiler-plate finally blocks.
Explanation
Resources declared in the try parentheses are closed in reverse order of their creation. Any exception thrown during resource closing is attached as a suppressed exception to the primary exception.
Code Example Java
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {\
    System.out.println(br.readLine());\
} catch (IOException e) {\
    System.out.println("Error reading file: " + e.getMessage());\
}
Reference: Java Exception Handling
Q 22

How does the try-catch-finally block work, and when does finally execute?

Easy
Answer
The try block contains code that might throw an exception, catch blocks handle specific exceptions, and the finally block contains code that always executes whether an exception is thrown or caught.
Explanation
The finally block executes guaranteed cleanup code (like closing streams or DB connections). It executes even if a return statement is present inside try or catch blocks, unless System.exit() is called or JVM crashes.
Code Example Java
FileInputStream fis = null;\
try {\
    fis = new FileInputStream("test.txt");\
} catch (FileNotFoundException e) {\
    System.out.println("File not found");\
} finally {\
    if (fis != null) {\
        try { fis.close(); } catch (IOException ignored) {}\
    }\
}
Reference: Java Exception Handling
Q 23

What is the difference between Throwable, Exception, and Error in Java?

Easy
Answer
Throwable is the root class of the Java exception hierarchy. Exception represents conditions that an application might want to catch, while Error represents serious system-level problems (e.g., OutOfMemoryError) that applications should not catch.
Explanation
Both Exception and Error extend Throwable. Errors are unchecked and usually fatal to JVM execution. Exceptions are further split into checked exceptions (direct subclasses of Exception) and unchecked exceptions (subclasses of RuntimeException).
Code Example Java
// Error handling is generally avoided:\
try {\
    recursiveMethod();\
} catch (StackOverflowError e) {\
    System.err.println("Call stack overflow occurred: " + e.getMessage());\
}
Reference: Java Exception Handling
Q 24

What is the difference between checked and unchecked exceptions?

Easy
Answer
Checked exceptions are verified at compile-time and must be caught or declared, whereas unchecked exceptions (RuntimeExceptions) occur at runtime and do not require explicit handling or declaration.
Explanation
Checked exceptions represent recoverable conditions outside application control (e.g., FileNotFoundException). Unchecked exceptions represent programming bugs or invalid states (e.g., NullPointerException, IllegalArgumentException).
Code Example Java
static String readFile() throws IOException {\
    return Files.readString(Path.of("data.txt"));\
}\
\
static void setAge(int age) {\
    if (age < 0) {\
        throw new IllegalArgumentException("Age cannot be negative");\
    }\
}
Reference: Java Exception Handling
Q 25

What is the best approach for exception logging in a layered application?

Answer
Log an exception at a layer that has enough context to make the log useful, and avoid logging the same exception repeatedly at every layer.
Explanation
Repeated logging can create duplicate stack traces and noisy logs. Lower layers should preserve and propagate the exception, while an application boundary or appropriate recovery layer can perform the main error logging.
Code Example Java
try {
    processOrder(order);
} catch (OrderProcessingException e) {
    logger.error(
        "Order processing failed for orderId={}\
}
Reference: \n order.getId()
Q 26

How should exceptions be handled across microservices?

Answer
A service should expose stable application-level error information rather than leaking internal exceptions, while preserving diagnostic details in its own logs.
Explanation
Remote callers should receive consistent error codes or structured responses. Technical exceptions such as SQL or socket failures should normally remain internal implementation details.
Code Example Java
try {
    inventoryClient.reserve(order);
} catch (HttpServerErrorException e) {
    throw new InventoryServiceException(
        "Inventory service is unavailable\
}
Reference: \n e\n );\n}""}"
Q 27

What is a compensation action in exception handling?

Answer
A compensation action reverses or offsets an earlier successful operation when a later operation fails and a single transaction cannot cover the entire workflow.
Explanation
Compensation is common in distributed workflows where database transactions cannot atomically include external services. It is a business recovery strategy rather than a simple catch block.
Code Example Java
reserveInventory(order);

try {
    chargePayment(order);
} catch (PaymentException e) {
    releaseInventory(order); // Compensation
    throw e;
}
Reference: Java Exception Handling
Q 28

How should exceptions be handled when a database operation fails after partial work?

Answer
The application should use transaction boundaries or compensation strategies so partial changes do not leave the system in an inconsistent state.
Explanation
Catching the exception and continuing blindly can commit or expose partial state. The correct solution depends on whether all operations can participate in one transaction or require distributed compensation.
Code Example Java
@Transactional
public void createOrder(Order order) {
    saveOrder(order);
    saveOrderItems(order);
    reserveInventory(order);

    // A failure should prevent an invalid partial transaction
    // from being committed.
}
Reference: Java Exception Handling
Q 29

What is idempotency and why is it important when retrying after exceptions?

Answer
An operation is idempotent when repeating it produces the same intended final result, making retries safer.
Explanation
For operations such as payments or order creation, a timeout can occur after the server has completed the operation. Retrying without idempotency protection can create duplicate side effects.
Code Example Java
String requestId = "PAY-12345";

try {
    paymentClient.charge(requestId
}
Reference: order);\n} catch (TimeoutException e) {\n // Retry only with an idempotent request key.\n retryPayment(requestId
Q 30

Why should not every exception be retried?

Answer
Some exceptions represent permanent failures such as invalid input, authorization failure, or violated business rules.
Explanation
Retrying permanent failures wastes resources and can repeatedly trigger side effects. Retry policies should be based on whether the failure is transient and whether the operation is safe to repeat.
Code Example Java
try {
    validateExam(exam);
} catch (InvalidExamException e) {
    // Do not retry invalid business input.
    throw e;
}
Reference: Java Exception Handling

About This Topic

Prepare for Exception Handling interviews with important concepts and commonly asked questions.