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 61

When is it acceptable to ignore an exception?

Medium
Answer
Ignoring an exception can be acceptable when the failure is explicitly known to be harmless and the decision is intentional.
Explanation
Even then, the code should make the reason clear. An empty catch block with no explanation is difficult to maintain because future developers cannot tell whether ignoring the exception was deliberate.
Code Example Java
try {
    Files.deleteIfExists(tempFile);
} catch (SecurityException e) {
    // Deliberately ignored only if cleanup failure is non-critical.
    logger.debug("Temporary file cleanup was not permitted\
}
Reference: e);\n}""}"
Q 62

What is exception swallowing?

Medium
Answer
Exception swallowing means catching an exception without properly reporting, recovering from, or propagating the failure.
Explanation
It is dangerous because the application may continue as though an operation succeeded even though it failed. A catch block should have a deliberate reason for not propagating a failure.
Code Example Java
try {
    sendNotification();
} catch (NotificationException e) {
    // Swallowed: caller may incorrectly assume success
}

markNotificationAsSent();
Reference: Java Exception Handling
Q 63

What is exception masking?

Hard
Answer
Exception masking occurs when one failure hides another failure that would have provided more useful diagnostic information.
Explanation
A common example is an exception from finally replacing the original exception from try. Exception masking can make production failures difficult to diagnose, so cleanup and error-handling code should preserve the primary failure whenever possible.
Code Example Java
try {
    throw new IOException("Database export failed");
} finally {
    throw new RuntimeException("Cleanup failed");
}
// The cleanup exception can mask the original failure.
Reference: Java Exception Handling
Q 64

Should exceptions be used for normal program flow?

Medium
Answer
Generally no. Exceptions should represent exceptional or invalid conditions rather than ordinary expected control flow.
Explanation
Using exceptions for normal branching can make code harder to read and may add unnecessary overhead. Prefer normal return values, conditions, Optional, or dedicated result types when the situation is expected.
Code Example Java
Optional<Student> student =
    studentRepository.findByEmail(email);

student.ifPresentOrElse(
    this::showStudent,
    this::showNotFound
);
Reference: Java Exception Handling
Q 65

Why is catching and rethrowing a different exception sometimes useful?

Medium
Answer
It is useful when a lower-level exception needs to be translated into a type that is meaningful to the current application layer.
Explanation
The new exception should add useful context and preserve the original exception as its cause. This keeps technical details available while giving higher layers a stable abstraction.
Code Example Java
try {
    paymentGateway.charge(order);
} catch (GatewayException e) {
    throw new PaymentProcessingException(
        "Unable to process order payment\
}
Reference: \n e\n );\n}""}"
Q 66

What is the difference between logging and handling an exception?

Medium
Answer
Logging records information about a failure, while handling means taking an appropriate action such as recovery, fallback, translation, or returning a meaningful response.
Explanation
Logging alone does not fix the failure. A method should not catch an exception merely to log it and then continue as though the operation succeeded unless that behavior is intentional and safe.
Code Example Java
try {
    publishResult(result);
} catch (PublishException e) {
    logger.error("Result publishing failed\
}
Reference: e);\n throw e;\n}""}"
Q 67

Why should we preserve the original exception cause when wrapping it?

Medium
Answer
Preserving the original cause keeps the lower-level failure information available for debugging and diagnosis.
Explanation
Without the cause, the new exception may tell the caller what failed at a high level but lose the technical reason that caused the failure.
Code Example Java
try {
    questionRepository.save(question);
} catch (SQLException e) {
    throw new QuestionPersistenceException(
        "Unable to save question\
}
Reference: \n e\n );\n}""}"
Q 68

Why should we not use an empty catch block?

Easy
Answer
An empty catch block silently discards the failure and makes diagnosis and recovery difficult.
Explanation
If an exception is caught, the code should normally take a meaningful action such as recovering, translating it, logging useful context, or deliberately ignoring a documented harmless condition.
Code Example Java
try {
    saveExam();
} catch (SQLException e) {
    // Bad: failure disappears silently
}
Reference: Java Exception Handling
Q 69

What is InterruptedException and how should it be handled?

Medium
Answer
InterruptedException indicates that a blocking thread was interrupted while waiting, sleeping, or performing an interruptible operation.
Explanation
A common best practice is to restore the thread's interrupted status when the current method cannot fully handle the interruption. Swallowing the interruption can break cooperative thread cancellation.
Code Example Java
try {
    queue.take();
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    return;
}
Reference: Java Exception Handling
Q 70

What is ExecutionException?

Medium
Answer
ExecutionException wraps an exception thrown by a task executed through an ExecutorService Future.
Explanation
The actual failure is available through getCause(). Code should inspect the cause when it needs to make a decision based on the original exception.
Code Example Java
try {
    future.get();
} catch (ExecutionException e) {
    Throwable cause = e.getCause();

    System.out.println(
        "Task failed because: " + cause.getMessage()
    );
}
Reference: Java Exception Handling
Q 71

How are exceptions handled in CompletableFuture?

Medium
Answer
CompletableFuture provides methods such as exceptionally, handle, and whenComplete for asynchronous exception processing.
Explanation
exceptionally can provide a fallback, handle can process both success and failure, and whenComplete is useful for observing completion without changing the result in the same way as handle.
Code Example Java
CompletableFuture
    .supplyAsync(() -> loadExam())
    .exceptionally(error -> {
        logger.error("Exam loading failed\
}
Reference: error);\n return defaultExam();\n });""}"
Q 72

How do you handle exceptions from ExecutorService tasks?

Medium
Answer
When using submit(), exceptions from a task are captured by the Future and become visible when get() is called.
Explanation
This is different from directly starting a Thread. The caller should inspect or handle ExecutionException and preserve its cause when appropriate.
Code Example Java
ExecutorService executor = Executors.newSingleThreadExecutor();

Future<String> future =
    executor.submit(() -> loadExam());

try {
    System.out.println(future.get());
} catch (ExecutionException e) {
    System.out.println("Task failed: " + e.getCause());
} finally {
    executor.shutdown();
}
Reference: Java Exception Handling
Q 73

What happens to an exception thrown by a thread?

Medium
Answer
An exception thrown from a thread does not automatically propagate to the thread that created it.
Explanation
The failing thread handles the uncaught exception according to its UncaughtExceptionHandler. If the result needs to be communicated to another thread, use mechanisms such as Future, CompletableFuture, or an explicit result channel.
Code Example Java
Thread worker = new Thread(() -> {
    throw new RuntimeException("Worker failed");
});

worker.start();
// The creator thread does not catch this with its own try-catch.
Reference: Java Exception Handling
Q 74

What is an UncaughtExceptionHandler?

Medium
Answer
UncaughtExceptionHandler is a callback mechanism that receives an uncaught exception from a thread.
Explanation
It can be used to record unexpected thread failures centrally. It should not be treated as a replacement for normal exception handling inside application logic.
Code Example Java
Thread.setDefaultUncaughtExceptionHandler(
    (thread, exception) -> {
        logger.error(
            "Thread " + thread.getName() + " failed\
}
Reference: \n exception\n );\n }\n);""}"
Q 75

What is an uncaught exception?

Easy
Answer
An uncaught exception is an exception for which no matching handler is found before the exception reaches the thread boundary.
Explanation
The thread's uncaught exception handler is then invoked. In a typical application, this usually results in logging the failure and termination of that thread.
Code Example Java
Thread worker = new Thread(() -> {
    throw new RuntimeException("Background task failed");
});

worker.start();
Reference: Java Exception Handling
Q 76

What happens if no catch block matches an exception?

Easy
Answer
The exception remains unhandled in the current method and propagates to the caller.
Explanation
Java searches the call stack for a suitable handler. If no handler is found before reaching the thread boundary, the thread's uncaught-exception mechanism handles the failure.
Code Example Java
static void service() {
    try {
        throw new IllegalArgumentException("Invalid exam ID");
    } catch (IOException e) {
        System.out.println("I/O problem");
    }
}

// IllegalArgumentException is not caught here
// and propagates to the caller.
Reference: Java Exception Handling
Q 77

Can a try block have only finally and no catch?

Easy
Answer
Yes. A try block may be followed directly by finally.
Explanation
This is commonly used when the method wants cleanup but does not want to handle the exception itself. After finally runs, the exception continues to the caller.
Code Example Java
try {
    databaseConnection.commit();
} finally {
    databaseConnection.close();
}
Reference: Java Exception Handling
Q 78

Can we have catch without finally?

Easy
Answer
Yes. A try block can have one or more catch blocks without a finally block.
Explanation
Use catch when the current layer needs to handle the failure. A finally block is optional and is needed only when cleanup must be performed regardless of success or failure.
Code Example Java
try {
    Integer.parseInt(input);
} catch (NumberFormatException e) {
    System.out.println("Invalid number");
}
Reference: Java Exception Handling
Q 79

Can we have a try block without catch but with finally?

Easy
Answer
Yes. Java allows try with finally and no catch.
Explanation
This form is useful when the current method does not handle the exception but still needs guaranteed cleanup. The exception continues to the caller after finally completes.
Code Example Java
Lock lock = serviceLock;

lock.lock();
try {
    updateStudent();
} finally {
    lock.unlock();
}
Reference: Java Exception Handling
Q 80

What happens when an exception occurs before the try block?

Medium
Answer
An exception thrown before entering a try block is not handled by that try block.
Explanation
Only code executed within the try block is protected by its catch handlers. If earlier code can fail and needs the same handling, it must be included in an appropriate protected section.
Code Example Java
Student student = studentRepository.findById(id);

try {
    System.out.println(student.getName());
} catch (NullPointerException e) {
    System.out.println("Student was not found");
}
Reference: Java Exception Handling
Q 81

Can a finally block contain a try-catch?

Medium
Answer
Yes. A finally block can contain a try-catch, although cleanup code should normally be kept simple.
Explanation
This pattern can be useful when cleanup itself can throw an exception and the application needs to handle that cleanup failure without hiding the original failure. Try-with-resources is preferable for AutoCloseable resources.
Code Example Java
try {
    processExam();
} finally {
    try {
        auditService.recordCompletion();
    } catch (AuditException e) {
        logger.warn("Audit cleanup failed\
}}
Reference: e);\n }\n}""}"
Q 82

Can a catch block contain another try-catch?

Medium
Answer
Yes. A catch block can contain another try-catch when handling the original exception requires an operation that can itself fail.
Explanation
The inner try-catch should have a clear purpose. For example, a recovery action may fail and need separate handling without replacing the main exception silently.
Code Example Java
try {
    processPayment();
} catch (PaymentException e) {
    try {
        notifyPaymentFailure();
    } catch (NotificationException notificationError) {
        logger.error("Could not send failure notification\
}}
Reference: \n notificationError);\n }\n}""}"
Q 83

What is a nested try-catch block?

Medium
Answer
A nested try-catch is a try-catch structure placed inside another try, catch, or finally block.
Explanation
Nested exception handling can be useful when an inner operation has a specific recovery strategy while the outer operation handles a broader failure. It should be used carefully because excessive nesting can make control flow difficult to understand.
Code Example Java
try {
    loadExam();

    try {
        validateQuestionBank();
    } catch (ValidationException e) {
        System.out.println("Question validation failed");
    }

} catch (IOException e) {
    System.out.println("Exam data could not be loaded");
}
Reference: Java Exception Handling
Q 84

What is the difference between getMessage() and printStackTrace()?

Easy
Answer
getMessage() returns the exception message, while printStackTrace() prints the exception type, message, and stack trace to the error output.
Explanation
getMessage() is useful when application code needs the exception's descriptive message, while printStackTrace() is mainly a diagnostic tool because it shows where the exception traveled through the call stack. In production applications, structured logging is usually preferred over directly calling printStackTrace().
Code Example Java
try {
    Integer.parseInt("Java");
} catch (NumberFormatException e) {
    System.out.println("Message: " + e.getMessage());
    e.printStackTrace();
}
Reference: Java Exception Handling
Q 85

What is precise rethrow?

Hard
Answer
Precise rethrow allows the compiler to infer the specific checked exceptions that can actually be rethrown from a catch block.
Explanation
When the caught exception is not reassigned, Java can use flow analysis to determine the narrower checked exceptions that may escape the method.
Code Example Java
static void process() throws IOException, SQLException {
    try {
        readAndSave();
    } catch (Exception e) {
        throw e;
    }
}
Reference: Java Exception Handling
Q 86

Can a static initializer throw a checked exception?

Hard
Answer
A static initializer cannot directly propagate a checked exception because there is no caller to handle it through a throws declaration.
Explanation
If initialization fails, application-specific code often wraps the failure in an unchecked exception or uses another initialization strategy that can report the failure explicitly.
Code Example Java
class AppConfig {
    static {
        try {
            loadConfiguration();
        } catch (IOException e) {
            throw new ExceptionInInitializerError(e);
        }
    }
}
Reference: Java Exception Handling
Q 87

Can a constructor declare throws?

Easy
Answer
Yes. A constructor can declare checked exceptions using throws.
Explanation
This is useful when object creation requires an operation that can fail, such as loading configuration or opening a file. The caller must then handle or propagate the checked exception.
Code Example Java
class Configuration {
    Configuration(Path file) throws IOException {
        String content = Files.readString(file);
        load(content);
    }
}
Reference: Java Exception Handling
Q 88

Can an overridden method throw unchecked exceptions?

Medium
Answer
Yes. An overriding method can throw unchecked exceptions without being restricted by the checked-exception declaration of the parent method.
Explanation
Unchecked exceptions are not part of the compiler-enforced throws contract, so an overriding method can introduce a RuntimeException subclass.
Code Example Java
class Parent {
    void validate() {}
}

class Child extends Parent {
    @Override
    void validate() {
        throw new IllegalStateException(
            "Child is not ready"
        );
    }
}
Reference: Java Exception Handling
Q 89

Can an overridden method throw a broader checked exception?

Hard
Answer
No. An overriding method cannot declare a broader checked exception than the method in the parent class.
Explanation
This rule preserves substitutability: callers using the parent type must remain safe under the contract defined by the parent method. The overriding method may throw fewer or narrower checked exceptions.
Code Example Java
class Parent {
    void load() throws IOException {}
}

class Child extends Parent {
    @Override
    void load() throws FileNotFoundException {
        // Allowed: FileNotFoundException is narrower
    }
}
Reference: Java Exception Handling
Q 90

Why are RuntimeExceptions unchecked?

Medium
Answer
RuntimeExceptions are unchecked because the Java language does not require every programming or state-related failure to be declared and caught.
Explanation
Forcing every such exception into method signatures would often make APIs unnecessarily verbose. Developers can still document, validate, and handle RuntimeExceptions when appropriate.
Code Example Java
static void calculateAverage(int total, int count) {
    if (count == 0) {
        throw new IllegalArgumentException(
            "Count must be greater than zero"
        );
    }

    System.out.println(total / count);
}
Reference: Java Exception Handling

About This Topic

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