Java Interview Preparation
Exception Handling Interview Questions
Java exceptions, custom errors, resources, Spring Boot handlers, transactions, Kafka, and production failures.
Exception Handling Interview Focus
Java exceptions, custom errors, resources, Spring Boot handlers, transactions, Kafka, and production failures.
Interview questions
1. What is an exception in Java? Beginner
An exception is an unexpected event that interrupts normal program flow. Java creates an exception object containing its type, message, location, and call sequence.
int result = 10 / 0; // ArithmeticException2. What is exception handling? Beginner
Exception handling detects runtime problems and responds gracefully using try, catch, finally, throw, and throws.
3. Why is exception handling important? Beginner
It prevents sudden termination, provides useful messages, separates error handling from business logic, releases resources, and supports logging and monitoring.
4. What is the exception hierarchy in Java? Intermediate
Throwable is the root of Error and Exception. RuntimeException represents unchecked exceptions, while IOException, SQLException, and ClassNotFoundException are common checked exceptions.
Object -> Throwable -> Error
-> Exception -> RuntimeException5. What is the difference between an exception and an error? Beginner
Exceptions are usually application-level problems that may be recoverable. Errors normally indicate serious JVM or system failures such as OutOfMemoryError and should rarely be handled.
6. What are checked exceptions? Beginner
Checked exceptions are verified by the compiler. The caller must handle them with try-catch or declare them with throws. IOException and SQLException are examples.
7. What are unchecked exceptions? Beginner
Unchecked exceptions extend RuntimeException and are not enforced by the compiler. They commonly represent invalid input, programming errors, or invalid state.
8. What is the difference between checked and unchecked exceptions? Beginner
Checked exceptions must be handled or declared and often represent external failures. Unchecked exceptions occur at runtime and commonly represent invalid code, input, or state.
9. What is a try block? Beginner
A try block contains code that may throw an exception and must be followed by catch, finally, or both.
try { int result = 100 / 0; } finally { cleanup(); }10. What is a catch block? Beginner
A catch block handles an exception thrown by its associated try block and can inspect methods such as getMessage, getCause, and printStackTrace.
11. What is a finally block? Beginner
finally contains cleanup code that normally runs whether the try succeeds or an exception is caught. Try-with-resources is preferred for closeable resources.
12. Is the finally block always executed? Intermediate
It normally executes, but not after System.exit, an unexpected JVM or operating-system termination, or a fatal process failure.
13. Can we use try without catch? Beginner
Yes. A try block may be followed by finally without catch. The exception is still propagated after cleanup.
try { process(); } finally { release(); }14. Can we use catch without try? Beginner
No. Every catch block must be associated with a try block, otherwise the code does not compile.
15. Can we use multiple catch blocks? Beginner
Yes. Multiple catch blocks allow different exception types to receive different recovery messages or actions.
try { process(); } catch (NumberFormatException e) { } catch (ArithmeticException e) { }16. What is the correct order of multiple catch blocks? Intermediate
Specific exception types must appear before general types. A catch(Exception) before catch(IOException) makes the latter unreachable.
17. What is multi-catch in Java? Beginner
Multi-catch handles unrelated exception types in one catch block when their handling logic is identical. It was introduced in Java 7.
catch (NumberFormatException | ArithmeticException exception) {
log.warn("Invalid number", exception);
}18. Can related exceptions be used in the same multi-catch? Intermediate
No. Multi-catch alternatives cannot have a parent-child relationship, such as IOException and FileNotFoundException. Use the parent type instead.
19. What is the throw keyword? Beginner
throw explicitly creates and raises one exception object, usually when input or a business rule is invalid.
if (age < 18) throw new IllegalArgumentException("Age must be at least 18");20. What is the throws keyword? Beginner
throws declares checked exceptions that a method may pass to its caller. The caller must handle or further declare them.
String readFile(String path) throws IOException { return Files.readString(Path.of(path)); }21. What is the difference between throw and throws? Beginner
throw raises an exception object inside code. throws declares exception types in a method signature and can list multiple types.
22. What is exception propagation? Intermediate
Exception propagation passes an unhandled exception up the method-call stack until a compatible handler is found or the JVM default handler terminates the thread.
23. Do checked and unchecked exceptions both propagate? Intermediate
Yes. Both can move through method calls. Checked exceptions must be handled or declared at required boundaries, while unchecked exceptions do not require declaration.
24. What is a custom exception? Beginner
A custom exception is a domain-specific exception created to express a business or application failure clearly.
class InsufficientBalanceException extends RuntimeException {
InsufficientBalanceException(String message) { super(message); }
}25. How do you create a checked custom exception? Beginner
Extend Exception and declare or handle it at the call site.
class InvalidFileFormatException extends Exception {
InvalidFileFormatException(String message) { super(message); }
}26. How do you create an unchecked custom exception? Beginner
Extend RuntimeException. The compiler does not force callers to handle or declare it.
class EmployeeNotFoundException extends RuntimeException { }27. When should checked exceptions be used? Intermediate
Use them when a caller can reasonably recover from an external condition such as a missing file, failed network connection, or unavailable resource.
28. When should unchecked exceptions be used? Intermediate
Use them for invalid arguments, violated business rules, missing entities, invalid application state, or failures that the current layer cannot meaningfully recover from.
29. What is try-with-resources? Beginner
Try-with-resources automatically closes resources implementing AutoCloseable or Closeable after the try block completes.
try (BufferedReader reader = Files.newBufferedReader(path)) {
return reader.readLine();
}30. What are the benefits of try-with-resources? Beginner
It reduces boilerplate, prevents resource leaks, closes resources reliably, and handles cleanup exceptions more safely than manual finally code.
31. Can multiple resources be declared in try-with-resources? Beginner
Yes. Resources are closed automatically in reverse order of declaration.
try (Reader reader = openReader(); Writer writer = openWriter()) { copy(reader, writer); }32. What is the AutoCloseable interface? Beginner
AutoCloseable marks a resource that can be closed automatically. Its close method may throw Exception and is invoked by try-with-resources.
class DatabaseSession implements AutoCloseable {
public void close() { }
}33. What is a suppressed exception? Advanced
If the try body throws and close also throws, the body exception is primary and the close exception is attached as suppressed through getSuppressed().
34. What happens when try and finally both return? Advanced
The return from finally overrides the return from try. Returning from finally is bad practice because it can hide exceptions and results.
static int value() { try { return 10; } finally { return 20; } }35. What happens when finally throws an exception? Advanced
An exception from finally can hide an exception from try or catch. Cleanup code should avoid throwing unless there is no safe alternative.
36. What is exception chaining? Intermediate
Exception chaining wraps a low-level exception in a higher-level exception while preserving the original cause for debugging.
throw new DataAccessException("Unable to load data", sqlException);37. Why should the original exception cause be preserved? Intermediate
The cause preserves the original stack trace, root-cause details, and debugging context needed for production diagnosis.
throw new RuntimeException("Database failed", exception);38. What is a stack trace? Beginner
A stack trace shows the exception type and the sequence of method calls, classes, files, and line numbers that led to the failure.
39. What is the difference between getMessage and printStackTrace? Beginner
getMessage returns only the exception message. printStackTrace prints the complete call sequence and should normally be replaced by a logging framework in production.
40. Why should printStackTrace be avoided in production? Intermediate
It writes unstructured output directly to standard error, may bypass centralized logging, cannot be controlled by log level, and may expose sensitive details.
41. What is the difference between final, finally, and finalize? Beginner
final prevents reassignment, overriding, or inheritance. finally provides cleanup flow. finalize is a deprecated cleanup callback and must not be used for resources.
42. Can we catch Throwable? Advanced
Technically yes, but it also catches serious Errors such as OutOfMemoryError and StackOverflowError. Catch specific exceptions instead.
43. Can we catch Error? Advanced
Technically yes, but catching Error does not guarantee safe recovery. Most Errors represent severe JVM or system failures.
44. Why is catching Exception everywhere bad practice? Intermediate
It handles unrelated failures together, hides programming errors, weakens recovery decisions, and makes debugging harder. Catch specific types instead.
45. What is exception swallowing? Beginner
Exception swallowing is catching an exception without logging, handling, or rethrowing it. It makes failures invisible and should be avoided.
catch (PaymentException exception) {
log.error("Payment failed", exception);
throw exception;
}46. Should exceptions be used for normal program flow? Intermediate
No. Validate predictable conditions normally and use exceptions for exceptional failures. Frequent exceptions create unnecessary stack traces and obscure intent.
47. Can an overriding method throw a checked exception? Advanced
It can throw the same checked exception, a narrower subclass, or none. It cannot throw a broader checked exception than the parent method.
48. Can an overriding method throw an unchecked exception? Intermediate
Yes. Unchecked exceptions are not restricted by the checked-exception overriding rules.
49. Can a constructor throw an exception? Beginner
Yes. A constructor can throw checked or unchecked exceptions. If it fails, the object is not created successfully.
Employee(String name) {
if (name == null) throw new IllegalArgumentException();
}50. Can a static initialization block throw an exception? Advanced
It can throw unchecked exceptions. A failure during class initialization may be reported as ExceptionInInitializerError.
51. How are exceptions handled in Spring Boot? Intermediate
They can be handled locally, with @ExceptionHandler, globally with @RestControllerAdvice, or translated into custom structured API errors. Centralized handling is preferred for REST APIs.
52. What is @ExceptionHandler in Spring Boot? Beginner
@ExceptionHandler maps a specified exception to a handler method in a controller or controller advice class.
@ExceptionHandler(EmployeeNotFoundException.class)
ResponseEntity<ApiError> handle(EmployeeNotFoundException ex) { return ResponseEntity.notFound().build(); }53. What is @ControllerAdvice? Beginner
@ControllerAdvice centralizes shared controller behavior, including exception handlers, across multiple controllers.
54. What is @RestControllerAdvice? Beginner
@RestControllerAdvice combines controller advice with response-body behavior and is commonly used for global REST API exception handling.
55. How do you create a standard API error response? Intermediate
Use a consistent object containing timestamp, status, safe error code, message, path, correlation ID, and validation field errors.
public record ApiError(Instant timestamp, int status, String errorCode, String message, String path) {}56. How should a not-found exception be handled in Spring Boot? Beginner
Throw a custom EmployeeNotFoundException from the service, handle it in global advice, and return a safe 404 response with a stable error code.
57. How are validation exceptions handled in Spring Boot? Intermediate
Handle MethodArgumentNotValidException in global advice, collect field errors, and return a structured 400 or 422 response.
58. What is the difference between business and system exceptions? Intermediate
Business exceptions represent known rule violations and usually map to 4xx responses. System exceptions represent technical failures and usually map to 5xx responses.
59. Should controllers contain large try-catch blocks? Beginner
Generally no. Keep controllers focused on HTTP mapping and let global advice translate service and domain exceptions consistently.
60. What HTTP status codes are commonly used for exceptions? Beginner
400 represents invalid input, 401 authentication, 403 access denial, 404 missing resources, 409 conflicts, 429 rate limits, 500 unexpected errors, and 503 unavailable dependencies.
61. How should exceptions be handled between microservices? Intermediate
Return safe structured errors with status, business code, message, timestamp, path, and correlation ID. Keep stack traces and internal details in secured server logs.
62. How do you handle downstream service failures? Advanced
Configure timeouts, classify client errors, retry only transient failures, use circuit breakers, preserve causes, log trace IDs, and avoid exposing downstream internals.
63. Should every exception be retried? Advanced
No. Retry transient timeouts or temporary unavailability with bounded exponential backoff. Do not retry validation, authentication, not-found, or non-idempotent failures without protection.
64. What is the role of a correlation ID? Intermediate
A correlation ID connects logs for one request across gateways, services, databases, Kafka, and downstream calls, making distributed failures traceable.
65. How should Kafka consumer exceptions be handled? Advanced
Classify transient and permanent failures, use bounded retry with backoff, dead-letter topics, idempotent processing, acknowledgements, and monitoring for retry and dead-letter counts.
66. What is a dead-letter topic? Intermediate
A dead-letter topic stores messages that still fail after configured retries so the main consumer can continue and operators can investigate or replay them.
67. What is a poison-pill message? Intermediate
A poison-pill message repeatedly fails because of invalid data, schema, or deserialization. It should be isolated after bounded retries instead of blocking the consumer forever.
68. How should database exceptions be handled? Advanced
Translate persistence failures into meaningful application exceptions, log safe context, propagate to global handling, and never expose SQL, credentials, schema details, or vendor messages.
69. What is exception translation in Spring? Advanced
Spring translates vendor-specific database failures into a consistent DataAccessException hierarchy, such as DuplicateKeyException and DataIntegrityViolationException.
70. How do exceptions affect Spring transactions? Advanced
By default, Spring rolls back for RuntimeException and Error but not for checked exceptions.
@Transactional
public void createOrder(Order order) {
repository.save(order);
throw new IllegalStateException("Failed");
}71. How do you roll back a Spring transaction for a checked exception? Advanced
Use @Transactional(rollbackFor = IOException.class) or another explicitly configured exception type.
@Transactional(rollbackFor = IOException.class)
public void importOrders() throws IOException { }72. What happens when an exception is caught inside a transactional method? Advanced
If a runtime exception is caught and swallowed, Spring may commit the transaction. Rethrow it or explicitly mark rollback when failure should undo the work.
73. How would you handle an employee-not-found scenario? Beginner
Throw a custom unchecked exception in the service, map it globally, and return a safe 404 Not Found response.
74. How would you handle a duplicate employee email? Advanced
Enforce a database unique constraint, translate DataIntegrityViolationException, and return 409 Conflict. A pre-check alone is unsafe under concurrency.
75. How would you handle an external API timeout? Advanced
Configure timeouts, retry safely with backoff, use a circuit breaker, preserve the cause, log correlation details, and return a safe service-unavailable response.
76. How would you handle exceptions in a scheduled job? Intermediate
Catch failures at the job boundary, log job and execution IDs, record metrics, isolate item failures when appropriate, retry transient work, and notify support for critical failures.
77. How would you handle an exception in asynchronous code? Advanced
Observe CompletableFuture or reactive failures with exceptionally, handle, or an equivalent error path. Do not allow asynchronous failures to disappear silently.
CompletableFuture.supplyAsync(service::load).exceptionally(error -> { log.error("Async failed", error); return List.of(); });78. How would you design exception handling for a layered application? Advanced
Repositories handle persistence details, services enforce business rules, controllers remain thin, global advice maps errors to responses, and logging/monitoring captures technical context.
79. What happens if no matching catch block is found? Beginner
The exception propagates to the caller. If nobody handles it, the JVM default handler prints details and terminates the affected thread.
80. What happens if an exception occurs inside a catch block? Intermediate
The new exception propagates unless another surrounding try-catch handles it. The original handler does not automatically handle failures created inside itself.
81. Can one exception handler handle multiple exception types? Beginner
Yes, multi-catch can handle unrelated exception types in one block when their handling logic is the same.
82. Can we rethrow an exception? Beginner
Yes. A handler can log and rethrow the same exception or wrap it in a higher-level exception while preserving the cause.
catch (PaymentException ex) { log.error("Payment failed", ex); throw ex; }83. Can a method declare an unchecked exception using throws? Beginner
Yes, but it is optional because the compiler does not require unchecked exceptions to be declared. It may still document the method contract.
84. Can the main method throw an exception? Beginner
Yes. An unhandled exception declared by main reaches the JVM default handler and normally terminates the application.
public static void main(String[] args) throws IOException { }85. Can we have nested try-catch blocks? Beginner
Yes, but excessive nesting makes control flow hard to understand. Prefer focused methods and specific handlers.
86. What are best practices for exception handling? Advanced
Catch specific exceptions, avoid empty catches, preserve causes, use custom domain errors, prefer try-with-resources, avoid finally returns, log safely, centralize REST handling, and distinguish retryable failures.
87. Should we log and rethrow the same exception? Intermediate
Usually not at every layer. Add context when wrapping and log once at the boundary that has enough business and technical context.
88. What information should be included in exception logs? Advanced
Include exception and stack trace, correlation and trace IDs, operation, safe business identifiers, downstream service, retry count, and duration. Never log credentials, tokens, or unmasked sensitive data.
89. What should not be returned to API clients? Beginner
Do not return stack traces, SQL, class names, file paths, internal addresses, credentials, tokens, or raw downstream errors. Return a safe structured error instead.
How to Prepare for Java Technical Interviews
Use this Java technical interview question bank to revise core concepts and practise explaining your decisions clearly. The questions cover Java fundamentals, object-oriented programming, collections, exceptions, multithreading, Spring Boot, Hibernate, databases, and other topics used in real software development interviews.
Start with the fundamentals, then move to scenario-based questions and advanced topics. Filter questions by difficulty to build confidence gradually. A strong answer should define the concept, explain why it matters, and include a practical example when appropriate.
Continue your preparation with the Java tutorials, or explore all interview preparation tracks for managerial and company-focused questions.
