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 31

What is exception handling in retry logic?

Answer
Retry logic should retry only failures that are transient and potentially recoverable, while permanent validation or business failures should normally fail immediately.
Explanation
Retries should also have limits, delays, and preferably backoff. Blindly retrying every exception can increase load and make an outage worse.
Code Example Java
for (int attempt = 1; attempt <= 3; attempt++) {
    try {
        externalService.call();
        break;
    } catch (TransientServiceException e) {
        if (attempt == 3) {
            throw e;
        }
        sleepBeforeRetry(attempt);
    }
}
Reference: Java Exception Handling
Q 32

How should InterruptedException be handled in production code?

Answer
If the current method cannot fully handle interruption, it should normally restore the thread's interrupted status and stop or propagate appropriately.
Explanation
Swallowing InterruptedException clears the interrupted status and can prevent higher-level cancellation logic from working correctly.
Code Example Java
try {
    queue.take();
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    logger.info("Worker interrupted");
    return;
}
Reference: Java Exception Handling
Q 33

Why can a try-catch around submit() fail to catch an ExecutorService task exception?

Answer
The task executes asynchronously after submit() returns, so the exception occurs in the worker thread rather than in the calling thread.
Explanation
With Future, the failure is captured and becomes visible through get(), usually wrapped in ExecutionException.
Code Example Java
try {
    Future<?> future = executor.submit(
        () -> { throw new IllegalStateException("Task failed"); }
    );

    future.get();
} catch (ExecutionException e) {
    System.out.println(e.getCause());
}
Reference: Java Exception Handling
Q 34

What is exception handling in asynchronous code?

Answer
Exceptions in asynchronous execution often cannot be handled by the caller's normal try-catch because the failure occurs on another execution path.
Explanation
The asynchronous API must provide a mechanism for observing or handling the failure, such as Future.get, CompletableFuture exceptionally, handle, or whenComplete.
Code Example Java
CompletableFuture
    .supplyAsync(() -> loadQuestions())
    .exceptionally(error -> {
        logger.error("Async load failed\
}
Reference: error);\n return List.of();\n });""}"
Q 35

How can Spring roll back a transaction for a checked exception?

Answer
Use transaction rollback configuration such as rollbackFor when a checked exception should also cause rollback.
Explanation
This is important when a business operation uses checked exceptions but still needs atomic transaction behavior.
Code Example Java
@Transactional(
    rollbackFor = IOException.class
)
public void importQuestions() throws IOException {
    saveQuestions();
    loadAdditionalData();
}
Reference: Java Exception Handling
Q 36

What is the default Spring transaction rollback behavior for RuntimeException?

Answer
By default, Spring transactions roll back for unchecked RuntimeException and Error, but not for checked exceptions.
Explanation
This behavior can be customized with rollbackFor and noRollbackFor. The exception design should therefore be considered together with transaction boundaries.
Code Example Java
@Transactional
public void createExam() {
    saveExam();
    throw new ExamStateException(
        "Exam cannot be activated"
    );
    // RuntimeException normally triggers rollback.
}
Reference: Java Exception Handling
Q 37

How do you handle exceptions in a transaction?

Answer
A transaction should normally roll back when a failure makes the unit of work invalid, while recoverable or intentionally handled conditions may be treated differently.
Explanation
In Spring, transaction rollback behavior depends on the exception and configuration. Developers should understand rollback rules instead of assuming every exception automatically causes rollback.
Code Example Java
@Transactional
public void registerStudent(Student student) {
    saveStudent(student);
    createInitialExamAttempt(student);

    // If the transaction fails, the unit of work
    // should normally be rolled back.
}
Reference: Java Exception Handling
Q 38

Why should stack traces not be returned to API clients?

Answer
Stack traces can expose internal class names, database details, file paths, and implementation information that clients do not need.
Explanation
The full exception should be logged securely on the server while the API returns a controlled error response. This improves security and keeps the API contract stable.
Code Example Java
@ExceptionHandler(Exception.class)
ResponseEntity<ApiError> handle(Exception e) {
    logger.error("Unexpected API failure\
}
Reference: e);\n\n return ResponseEntity\n .status(500)\n .body(new ApiError(\""INTERNAL_ERROR\""
Q 39

How should a REST API handle exceptions?

Answer
A REST API should convert application exceptions into consistent HTTP responses without exposing internal implementation details.
Explanation
A centralized exception handler can map domain failures to appropriate status codes and response bodies. Unexpected failures should be logged and returned as a safe generic error rather than exposing stack traces or database details.
Code Example Java
@RestControllerAdvice
class ApiExceptionHandler {

    @ExceptionHandler(StudentNotFoundException.class)
    ResponseEntity<ApiError> handle(
            StudentNotFoundException e) {

        return ResponseEntity.status(404)
            .body(new ApiError("STUDENT_NOT_FOUND" 
                               e.getMessage()));
    }
}
Q 40

What is the difference between a technical exception and a business exception?

Answer
A technical exception represents an infrastructure or implementation failure, while a business exception represents a domain rule or business condition.
Explanation
Database connection failures, I/O failures, and network errors are technical examples. Conditions such as ExamAlreadySubmitted or InsufficientBalance represent business rules. Keeping these concepts separate improves application architecture.
Code Example Java
if (exam.isSubmitted()) {
    throw new ExamAlreadySubmittedException(
        "Exam has already been submitted"
    );
}

try {
    examRepository.save(exam);
} catch (SQLException e) {
    throw new ExamPersistenceException(
        "Unable to save exam" 
        e
    );
}
Q 41

When should an exception be translated into a custom exception?

Answer
Translate an exception when the lower-level exception is too specific to the implementation and the current layer needs to expose a meaningful abstraction.
Explanation
For example, a repository can translate SQLException into StudentPersistenceException. The original cause should be preserved so diagnostic information is not lost.
Code Example Java
try {
    return studentRepository.findById(id);
} catch (SQLException e) {
    throw new StudentPersistenceException(
        "Unable to load student " + id 
        e
    );
}
Q 42

When should an exception be propagated instead of caught?

Answer
An exception should be propagated when the current layer cannot meaningfully recover from the failure.
Explanation
Catching an exception only to log it or rethrow it unchanged often adds little value. Let a layer that has enough context make the recovery decision, while lower layers can translate technical failures when a better abstraction is needed.
Code Example Java
public Student getStudent(long id) {
    return repository.findById(id);
    // Let the appropriate higher layer handle the failure
}
Reference: Java Exception Handling
Q 43

What is the difference between handling an exception and recovering from an exception?

Answer
Handling an exception means deciding what to do when a failure occurs, while recovery means successfully restoring the application to a valid state or providing a safe alternative.
Explanation
A catch block is not automatically recovery. Logging an exception and returning an error response is handling, but true recovery means the application can safely continue, retry, compensate, or provide a valid fallback. This distinction is important in senior-level design discussions.
Code Example Java
try {
    paymentService.charge(order);
} catch (PaymentException e) {
    logger.warn("Payment failed" e);
    showPaymentFailure();
}
Q 44

How should exceptions be handled in batch processing?

Hard
Answer
Batch applications should distinguish between failures that should stop the job and failures that can be recorded and skipped according to business requirements.
Explanation
For example, one invalid question may be skipped and reported while a database outage may require the batch step to stop. The handling strategy should be based on the type and recoverability of the failure rather than catching everything.
Code Example Java
for (Question question : questions) {
    try {
        importQuestion(question);
    } catch (InvalidQuestionException e) {
        logger.warn(
            "Skipping invalid question {}\
}}
Reference: \n question.getId()
Q 45

How do you preserve an exception while adding context?

Medium
Answer
Create a new exception containing the additional context and pass the original exception as its cause.
Explanation
This gives the caller a meaningful message from the current layer while retaining the original failure for diagnosis. It is preferable to replacing the original exception without a cause.
Code Example Java
try {
    uploadDocument(document);
} catch (IOException e) {
    throw new DocumentProcessingException(
        "Failed to upload document " + document.getId()
}
Reference: \n e\n );\n}""}"
Q 46

Should sensitive information be included in exception messages?

Easy
Answer
No. Exception messages and logs should not expose passwords, access tokens, secrets, or other sensitive information.
Explanation
Failures should contain enough context to diagnose the problem without leaking confidential data. Sensitive values can also accidentally appear in centralized logging systems.
Code Example Java
try {
    authenticate(username, password);
} catch (AuthenticationException e) {
    logger.warn(
        "Authentication failed for user {}\
}
Reference: \n username\n );\n // Never log the password or access token.\n}""}"
Q 47

Why should exception messages contain useful context?

Medium
Answer
Useful exception messages explain what operation failed and provide relevant context without exposing sensitive information.
Explanation
A message such as 'Save failed' is often less useful than identifying the operation and non-sensitive identifier. Do not place passwords, tokens, or other secrets into exception messages or logs.
Code Example Java
throw new StudentPersistenceException(
    "Unable to save student with id " + studentId
);
Reference: Java Exception Handling
Q 48

How should exceptions be handled in a repository layer?

Medium
Answer
A repository should normally deal with persistence-specific failures and either propagate them or translate them into a suitable application abstraction.
Explanation
Repository code understands database or storage failures better than controllers do. It should preserve the original cause when translating technical exceptions.
Code Example Java
try {
    return jdbcTemplate.queryForObject(
        sql,
        studentRowMapper,
        id
    );
} catch (DataAccessException e) {
    throw new StudentPersistenceException(
        "Database lookup failed\
}
Reference: e\n );\n}""}"
Q 49

How should exceptions be handled in a service layer?

Medium
Answer
The service layer should handle an exception when it can recover or make a meaningful business decision; otherwise it should propagate or translate it.
Explanation
The service layer should avoid exposing unnecessary infrastructure details to higher layers. For example, a SQLException can be translated into an application-specific persistence exception while preserving the cause.
Code Example Java
public Student findStudent(long id) {
    try {
        return repository.findById(id);
    } catch (SQLException e) {
        throw new StudentPersistenceException(
            "Unable to load student " + id e
        );
    }
}
Q 50

What is a global exception handler?

Medium
Answer
A global exception handler centralizes handling for exceptions that cross an application boundary, especially in web applications.
Explanation
In Spring applications, @RestControllerAdvice and @ExceptionHandler are commonly used to avoid repeating the same error-response logic in every controller.
Code Example Java
@RestControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    ResponseEntity<String> handle(IllegalArgumentException e) {
        return ResponseEntity.badRequest()
            .body(e.getMessage());
    }
}
Reference: Java Exception Handling
Q 51

What is exception handling at an application boundary?

Hard
Answer
An application boundary is a location where low-level exceptions are converted into an appropriate external response, log entry, or process-level action.
Explanation
A REST controller, message consumer, or scheduled job can act as a boundary. Lower layers can propagate meaningful exceptions while the boundary decides how they should be presented externally.
Code Example Java
@RestControllerAdvice
class ApiExceptionHandler {

    @ExceptionHandler(StudentNotFoundException.class)
    ResponseEntity<String> handle(
            StudentNotFoundException e) {

        return ResponseEntity
            .status(404)
            .body(e.getMessage());
    }
}
Reference: Java Exception Handling
Q 52

What is the difference between rethrowing and wrapping an exception?

Medium
Answer
Rethrowing sends the same exception onward, while wrapping creates a new exception and normally preserves the original as its cause.
Explanation
Rethrow when the existing exception type is already appropriate for the caller. Wrap when the current layer needs to expose a more meaningful abstraction or add domain context.
Code Example Java
try {
    repository.save(order);
} catch (SQLException e) {
    throw new OrderPersistenceException(
        "Unable to persist order\
}
Reference: e\n );\n}""}"
Q 53

What happens to the stack trace when an exception is rethrown?

Hard
Answer
If the same exception object is rethrown, its original exception information is preserved rather than creating an unrelated failure.
Explanation
Rethrowing with throw e preserves the exception object and its cause chain. Creating a new exception without the original cause can lose valuable diagnostic information.
Code Example Java
try {
    processOrder();
} catch (OrderException e) {
    logger.error("Order processing failed\
}
Reference: e);\n throw e;\n}""}"
Q 54

What is a stack trace?

Easy
Answer
A stack trace describes the sequence of method calls that led to an exception.
Explanation
It helps developers identify where the failure originated and how execution reached that point. When an exception is wrapped and its cause is preserved, the stack trace can show both the higher-level and lower-level failures.
Code Example Java
static void controller() {
    service();
}

static void service() {
    repository();
}

static void repository() {
    throw new RuntimeException("Database failure");
}
Reference: Java Exception Handling
Q 55

What information does printStackTrace() provide?

Easy
Answer
printStackTrace() prints the exception type, message, and stack trace showing the call path where the exception propagated.
Explanation
It is useful for diagnosis during development, but production applications normally use structured logging so the exception can be correlated with requests and other application data.
Code Example Java
try {
    loadQuestions();
} catch (IOException e) {
    e.printStackTrace();
}
Reference: Java Exception Handling
Q 56

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

Easy
Answer
getMessage() returns the descriptive message of the current exception, while getCause() returns the exception that caused it.
Explanation
They provide different information. The message describes the current failure, while the cause helps trace the failure back to a lower-level operation.
Code Example Java
SQLException databaseError =
    new SQLException("Connection refused");

RuntimeException serviceError =
    new RuntimeException("Unable to load students\
Reference: \n databaseError);\n\nSystem.out.println(serviceError.getMessage());\nSystem.out.println(serviceError.getCause());""}"
Q 57

What is initCause()?

Medium
Answer
initCause() explicitly sets the cause of an exception after the exception object has been created.
Explanation
It can be useful when an exception type does not provide a constructor accepting a cause. The cause can normally be initialized only once, so it should be set deliberately.
Code Example Java
IOException cause = new IOException("File unavailable");

RuntimeException failure =
    new RuntimeException("Exam loading failed");

failure.initCause(cause);

System.out.println(failure.getCause());
Reference: Java Exception Handling
Q 58

What is the purpose of getCause()?

Easy
Answer
getCause() returns the original cause associated with an exception, if one exists.
Explanation
It is especially useful with exception chaining because a high-level exception can preserve the lower-level failure. Inspecting the cause helps diagnose the actual technical reason behind the higher-level failure.
Code Example Java
try {
    repository.save(student);
} catch (SQLException e) {
    throw new StudentPersistenceException("Save failed\
}
Reference: e);\n} catch (StudentPersistenceException e) {\n System.out.println(\""Cause: \"" + e.getCause());\n}""}"
Q 59

Why should we avoid catching Throwable?

Medium
Answer
Throwable includes both Exception and Error, so catching it can accidentally intercept serious JVM failures that application code normally should not handle.
Explanation
Catching Throwable should be limited to specialized infrastructure where there is a strong reason to observe every failure. Normal business code should generally catch appropriate Exception types instead.
Code Example Java
try {
    executeBusinessOperation();
} catch (Exception e) {
    logger.error("Business operation failed\
}
Reference: e);\n}""}"
Q 60

What is the best practice for catching a specific exception instead of Exception?

Easy
Answer
Catch the most specific exception that the current layer can meaningfully handle.
Explanation
Specific catches make recovery behavior clearer and prevent unrelated programming errors from being accidentally treated as expected failures.
Code Example Java
try {
    Integer.parseInt(input);
} catch (NumberFormatException e) {
    System.out.println("Invalid number");
}
Reference: Java Exception Handling

About This Topic

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