30+ Exception Handling Interview Questions and Answers in 2025 [Freshers & Experienced]
By Rohan Vats
Updated on Jun 13, 2025 | 56 min read | 39.75K+ views
Share:
For working professionals
For fresh graduates
More
By Rohan Vats
Updated on Jun 13, 2025 | 56 min read | 39.75K+ views
Share:
Did you know? Even strong candidates with a solid technical score of 3 out of 4 can fail up to 22% of technical interviews like tough questions or biased evaluations. That’s why exception handling often turns out to be the make-or-break topic that separates top performers from the rest. |
Exception handling interview questions are a common focus in technical interviews, often covering key areas such as try-catch-finally usage, custom exceptions, and exception propagation. Interviewers may also explore your familiarity with real-time monitoring and logging tools like Sentry, Log4j, or Stackdriver, which are essential for maintaining stability in production systems.
However, many candidates struggle to deliver clear, structured answers, especially to scenario-based questions that test both conceptual clarity and practical application.
In this blog, you'll find 30+ Java's exception handling interview questions and answers for 2025, carefully selected to help freshers and experienced professionals build a strong understanding of core concepts.
Understanding exception handling is essential for freshers aiming to succeed in technical interviews. Employers expect candidates to be familiar with core concepts such as try-catch in Java, exception hierarchy, custom exceptions, and the distinction between checked and unchecked exceptions. They also value a clear understanding of how to handle exceptions gracefully to ensure code stability and user-friendly error reporting.
If you want to strengthen your skills and stand out in competitive software development roles, consider these top-rated upGrad programs. Each course is designed to build in-demand expertise that employers seek in today's tech field:
To make your interview preparation easier, we’ve compiled a comprehensive list of frequently asked exception handling interview questions and answers. It includes practical examples and tips to help you demonstrate strong problem-solving skills and write reliable code.
How to Answer:
Sample Answer:
Exception handling in Java is a reliable mechanism to manage runtime errors so that the normal flow of the application is not disrupted. It enables developers to write error-resilient code by catching and handling exceptions gracefully. Java provides five key constructs for exception handling:
There are two main types of exceptions in Java:
Exception handling improves application reliability, maintainability, and user experience, especially in production environments like APIs, file systems, or database operations.
Code Example:
public class Example {
public static void main(String[] args) {
try {
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Finally block executed");
}
}
}
Code Explanation:
Output:
Error: / by zero
Finally block executed
Output Explanation:
How to Answer:
Sample Answer:
In Java, both Error and Exception are subclasses of the Throwable class, but they serve very different purposes. An Error represents serious issues that are beyond the control of the application, typically related to system-level failures like JVM crashes or memory overflow. These are not meant to be caught or handled in code because recovery is usually not possible.
For example, something like an OutOfMemoryError or a StackOverflowError falls under this category.
On the other hand, an Exception represents conditions that the application can handle and recover from. Exceptions are part of the normal program flow when something goes wrong. Exceptions are further divided into two main types:
So, in short:
Code Example:
public class ErrorVsException {
public static void main(String[] args) {
try {
int[] arr = new int[2];
System.out.println(arr[5]); // This line throws ArrayIndexOutOfBoundsException
} catch (Exception e) {
System.out.println("Handled Exception: " + e);
}
}
}
Code Explanation:
Output Explanation: The output confirms that the exception was caught and handled.
Handled Exception: java.lang.ArrayIndexOutOfBoundsException: 5
Note: Errors like StackOverflowError or OutOfMemoryError stem from critical system failures (e.g., infinite recursion or memory leaks). They're not meant to be caught with try-catch and should be avoided through proper design and resource management. |
How to Answer:
Sample Answer:
In Java, exceptions are categorized into checked and unchecked based on when they are detected by the compiler.
In short, checked exceptions ensure that the programmer thinks about error handling during compilation, while unchecked exceptions are more flexible but can crash the application if not handled properly.
Code Example:
import java.io.*;
public class CheckedUnchecked {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("abc.txt"); // Checked Exception
} catch (FileNotFoundException e) {
System.out.println("Checked Exception: " + e);
}
int[] a = new int[2];
System.out.println(a[5]); // Unchecked Exception
}
}
Code Explanation:
Output Explanation (Assuming abc.txt doesn’t exist):
Checked Exception: java.io.FileNotFoundException: abc.txt (No such file or directory)
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 2
Checked exceptions improve reliability by enforcing error handling at compile time. However, overusing them may clutter the code. Use checked exceptions for recoverable conditions and unchecked for programming logic errors.
How to Answer:
Sample Answer:
The try-catch is used to handle exceptions that may occur during program execution, particularly at runtime. The goal is to prevent the application from crashing by gracefully handling errors and allowing the program to continue or exit safely.
Here’s how it works:
For example, dividing a number by zero would normally crash the program. But with try-catch, we can intercept that and respond accordingly
Code Example:
public class TryCatchExample {
public static void main(String[] args) {
try {
int a = 10 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Handled: " + e.getMessage());
}
}
}
Code Explanation:
Output: The exception is caught and the message "/ by zero" (from e.getMessage()) is displayed. If not handled, this would have caused the program to terminate abnormally.
Handled: / by zero
Always catch the most specific exceptions first. Avoid catching generic Exception unless absolutely necessary. This improves clarity and error resolution.
How to Answer:
Sample Answer:
In Java, the finally block is used to write code that should always be executed, regardless of whether an exception is thrown or caught. It is typically placed after the try and catch blocks and is most commonly used for cleaning up resources, like closing file streams, releasing database connections, or unlocking locks.
One of the key advantages of finally is that it guarantees execution, even if the code in the try or catch block includes a return statement. The only exception to this behavior is if the JVM shuts down abruptly using System.exit() or due to a fatal error.
So, finally block ensures your program leaves resources in a clean state, which is crucial for avoiding memory leaks or corrupted states.
Code Example:
public class FinallyExample {
public static void main(String[] args) {
try {
int a = 10 / 0; // Will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught: " + e);
} finally {
System.out.println("Finally executed");
}
}
}
Code Explanation:
Output: The first line of the output indicates that the ArithmeticException was successfully caught in the catch block and its details were printed. The second line confirms that the finally block was executed immediately afterward, demonstrating that it runs regardless of whether an exception was thrown or not.
This ensures any cleanup code placed in finally will always be executed, maintaining application stability.
Caught: java.lang.ArithmeticException: / by zero
Finally executed
Use finally to release system resources. It runs even if return is used in try/catch, making it ideal for cleanup logic like file or socket closing.
How to Answer:
Sample Answer:
throw and throws are both used in exception handling, but they serve different roles.
upGrad’s Exclusive Software and Tech Webinar for you –
SAAS Business – What is So Different?
For example, if a method checks user age and wants to stop execution for underage input, it can throw an exception. That same method may use throws to declare the exception it might throw.
Code Example:
public class ThrowThrows {
static void validate(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Not valid age");
}
}
public static void main(String[] args) {
try {
validate(15);
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
Code Explanation:
Output: The output prints the message from the thrown exception: "Caught: Not valid age". This confirms that the exception was explicitly thrown using throw, and properly declared in the method using throws, then caught and handled in the catch block.
Caught: Not valid age
Use throw to trigger exceptions conditionally inside code, and throws to notify the calling method that it must handle or further declare the exception.
Also Read: Top 10 Free Java Courses with Certificates for In-Demand Java Jobs
How to Answer:
Sample Answer:
The try-with-resources statement was introduced in Java 7 to simplify resource management and ensure resources are closed automatically. In Java, a resource refers to an object like a BufferedReader, FileInputStream, or Connection, basically anything that implements the AutoCloseable interface.
When you use such resources inside a try block using try-with-resources, Java guarantees that they will be closed automatically once the try block finishes, whether it ends normally or due to an exception. This eliminates the need for manual finally blocks and helps prevent resource leaks, especially in file handling or database operations.
Code Example:
import java.io.*;
public class TryWithResources {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
}
Code Explanation:
Output Explanation (Assuming test.txt has one line "Hello"):
The program reads and prints the first line of the file. The file stream is closed automatically after the try block.
Hello
Note: You can declare multiple resources in a single try-with-resources block, separated by semicolons. This is cleaner, safer, and preferred in modern Java coding practices. |
How to Answer:
Sample Answer:
Yes, Java allows multiple catch blocks to handle different types of exceptions. This feature is helpful when you need to handle distinct exceptions differently within the same try-catch structure.
The order of the catch blocks is crucial, the most specific exceptions (e.g., ArithmeticException) should come first, followed by the more general exceptions (e.g., Exception), as Java will stop at the first block that matches the thrown exception type.
Code Example:
public class MultiCatch {
public static void main(String[] args) {
try {
int[] arr = new int[5]; // Creates an array of size 5
arr[5] = 10 / 0; // ArithmeticException (division by zero) and ArrayIndexOutOfBoundsException (accessing index 5)
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception"); // Handles the division by zero exception
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Exception"); // Handles the array index out-of-bounds exception
} catch (Exception e) {
System.out.println("Generic Exception"); // Handles any other exceptions
}
}
}
Code Explanation:
Output Explanation: The program prints "Arithmetic Exception" because the first exception that occurs is the division by zero, which is caught by the catch (ArithmeticException e) block.
Arithmetic Exception
Note: From Java 7 onward, you can also use multi-catch (catch (IOException | SQLException e)) to handle multiple exceptions with the same logic, but avoid mixing unrelated types in one block for clarity. |
How to Answer:
Sample Answer:
In Java, the base class for all exceptions and errors is Throwable. It defines everything that can be thrown using throw and caught using catch.
Throwable has two direct subclasses:
So while Exception is the base class for most handled exceptions in Java, it's actually Throwable that sits at the top of the hierarchy and is essential for Java's exception handling mechanism.
Class Hierarchy Diagram (Text View):
java.lang.Object
↳ java.lang.Throwable
↳ java.lang.Exception
↳ IOException, SQLException, etc.
↳ java.lang.Error
↳ OutOfMemoryError, StackOverflowError, etc.
Explanation:
Real-World Analogy:
This is important because only classes that extend Throwable can be thrown using the throw keyword and caught using a catch block. The Java compiler enforces this rule to ensure only valid exception types are handled.
How to Answer:
Sample Answer:
If an exception occurs and there's no catch block to handle it, Java's runtime environment will try to propagate the exception up the call stack. If none of the calling methods handle it either, the exception eventually reaches the JVM, which then:
This is why it's important to handle exceptions properly to ensure smooth and predictable application behavior.
Code Example:
public class NoCatchBlock {
public static void main(String[] args) {
int a = 5 / 0; // no catch block to handle ArithmeticException
System.out.println("After exception"); // this line will not execute
}
}
Code Explanation:
Output: The output shows the exception details:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at NoCatchBlock.main(NoCatchBlock.java:3)
This demonstrates the importance of properly handling exceptions in order to prevent the abrupt termination of the program and allow for smoother execution.
How to Answer:
Sample Answer:
No, in Java, you cannot write a try block by itself. A try block must be followed by:
If you write a try block without either, the code will result in a compile-time error. However, using try with just a finally block is legal and often used when you want to guarantee resource cleanup even if an exception occurs and you don't want to handle it directly.
Code Example:
public class TryWithoutCatch {
public static void main(String[] args) {
try {
int result = 10 / 0; // Exception occurs
} finally {
System.out.println("Finally block executed");
}
}
}
Code Explanation:
Output:
Finally block executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
How to Answer:
Sample Answer:
Yes, from Java 7 onwards, you can catch multiple exceptions in a single catch block using the pipe (|) symbol. This is known as multi-catch and is useful when different exceptions require the same handling logic. For example: catch (IOException | SQLException e)
This approach helps reduce code duplication and makes the code cleaner."
Code:
public class MultiCatchBlock {
public static void main(String[] args) {
try {
String text = null;
System.out.println(text.length()); // NullPointerException
} catch (NullPointerException | ArithmeticException e) {
System.out.println("Caught Exception: " + e);
}
}
}
Code Explanation:
Output:
“Caught Exception: java.lang.NullPointerException”: The NullPointerException is thrown because we try to invoke the length() method on a null reference. The catch block successfully catches the exception and prints the message "Caught Exception: " followed by the exception's class name (java.lang.NullPointerException).
Caught Exception: java.lang.NullPointerException
The multi-catch block catches the NullPointerException and executes the logic, printing the exception details. If an ArithmeticException had occurred, it would also be caught by the same block, but here, only the NullPointerException is thrown and handled.
Looking to excel in exception handling in JavaScript? Begin with upGrad's JavaScript Basics from Scratch Course. You'll lay a strong base in key concepts like variables, data types and functions. Enroll now and acquire the core skills to succeed in coding!
How to Answer:
Sample Answer:
Exception propagation refers to the process where an exception moves up the method call stack until it is caught or reaches the JVM.
This is useful when you want to handle exceptions at a higher level instead of in every method.
Code:
public class ExceptionPropagation {
static void methodA() {
int result = 10 / 0; // Throws ArithmeticException
}
static void methodB() {
methodA(); // Doesn't handle
}
public static void main(String[] args) {
methodB(); // Doesn't handle
}
}
Code Explanation:
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionPropagation.methodA(ExceptionPropagation.java:3)
at ExceptionPropagation.methodB(ExceptionPropagation.java:7)
at ExceptionPropagation.main(ExceptionPropagation.java:11)
Also Read: Exception Handling in Python: Handling Exception Using Try Except
How to Answer:
Sample Answer:
Yes, Java allows rethrowing an exception from a catch block. This means after catching and possibly logging or processing an exception, you can pass it on for further handling. You can rethrow the same exception, or throw a new custom exception (often wrapping the original).
This is often used in layered applications where exceptions are caught in lower layers but should be handled by upper layers.
Code:
public class RethrowExample {
public static void main(String[] args) {
try {
throw new NullPointerException("Original exception");
} catch (NullPointerException e) {
System.out.println("Logging: " + e.getMessage());
throw e; // Rethrowing
}
}
}
Code Explantion:
Output:
Logging: Original exception
Exception in thread "main" java.lang.NullPointerException: Original exception
This demonstrates how the exception is propagated after being rethrown.
Also Read: 50 Java Projects With Source Code in 2025: From Beginner to Advanced
How to Answer:
Sample Answer:
In Java, final, finally, and finalize are three distinct concepts, and here's how they differ:
final int x = 10; // x cannot be reassigned
try {
// Code that might throw an exception
} finally {
// Always runs, for cleanup
System.out.println("This will always execute.");
}
@Override
protected void finalize() throws Throwable {
// Cleanup code before garbage collection
}
Each of these plays a very different role in Java, so it's important to understand when and why to use them in your code.
Code Snippet (Combined):
final int x = 10; // final keyword
try {
int a = 5 / 0;
} finally {
System.out.println("This always executes"); // finally block
}
@Override
protected void finalize() throws Throwable {
System.out.println("Finalize called"); // finalize method
}
Code Explanation:
Output:
This always executes
Note: The program will definitely print "This always executes" due to the finally block, but "Finalize called" will only be printed if the garbage collector runs during program execution, which is not guaranteed in this short program. |
This concludes our exploration of essential exception handling interview questions and answers, relevant for freshers aiming to strengthen their technical proficiency.
Level up your coding and programming skills with upGrad’s Generative AI Mastery Certificate for Software Development. Learn to integrate generative AI into your projects, build smarter apps, and gain in-demand skills through hands-on learning.
Let’s now move on to advanced exception handling concepts with questions designed specifically for experienced professionals and practical scenarios.
Exception handling is a key skill in software development interviews, especially for roles involving Java, Python, or C#. Interviewers often test your understanding of concepts like custom exceptions, exception propagation, and error handling patterns.
Here are a few exception handling interview questions and answers for experienced candidates. It covers advanced topics with clear code examples, outputs, and detailed explanations to help you prepare effectively.
How to Answer:
Sample Answer:
In a layered architecture (like MVC), follow a bottom-up exception propagation strategy where exceptions thrown in lower layers (e.g., DAO) bubble up to higher layers (e.g., Service, Controller). Each layer can either handle the exception or propagate it further wrapped in a custom exception.
At the controller level (especially in Spring Boot), use @ControllerAdvice to globally handle exceptions and return structured error responses using @ExceptionHandler.
This keeps the controller clean and separates concerns while ensuring consistent error responses.
Code Example:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
ErrorResponse error = new ErrorResponse("NOT_FOUND", ex.getMessage());
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
}
Code Explanation:
Output:
{
"errorCode": "NOT_FOUND",
"message": "Resource with ID 123 not found"
}
How to Answer:
Sample Answer:
Exception chaining is a technique in Java where an exception is wrapped or "chained" inside another exception. This allows you to propagate the original exception's cause while throwing a new, more specific exception. It preserves the root cause and stack trace, making it easier to debug the issue later.
Exception chaining is useful when you want to translate lower-level exceptions (like SQLException) into higher-level domain-specific exceptions (like DataAccessException) while still keeping the original exception information for debugging.
Code Example:
public class ServiceLayer {
public void process() {
try {
dao.fetchData();
} catch (SQLException e) {
throw new DataAccessException("Error fetching data", e);
}
}
}
Code Explanation:
Output Explanation:
DataAccessException: Error fetching data
at ServiceLayer.process(ServiceLayer.java:5)
Caused by: java.sql.SQLException: Database connection error
at Dao.fetchData(Dao.java:10)
at ServiceLayer.process(ServiceLayer.java:4)
How to Answer:
Sample Answer:
In scalable systems, exception logging should be structured, centralized, and efficient. Instead of plain text logs, structured logging (often in JSON format) is used to include rich metadata like timestamps, log levels, request IDs, and exception types. This makes it easier to aggregate and analyze logs across distributed services.
To maintain performance and observability, logs should be non-blocking, sanitized, and traceable across services. Asynchronous appenders can prevent logging from slowing down the application. Including correlation IDs helps trace logs through microservices during debugging or incident analysis.
Code Example:
private static final Logger logger = LoggerFactory.getLogger(MyService.class);
try {
// some logic
} catch (Exception e) {
logger.error("Error occurred while processing orderId={} ", orderId, e);
throw e;
}
How to Answer:
Sample Answer:
Custom exception hierarchies are used to group related exceptions by extending a common base class. This approach improves code clarity, simplifies error handling, and supports both broad exception catching and fine-grained control. It also allows higher layers of the application to handle categories of errors uniformly while still supporting specific behaviors.
Code Example:
public class ApplicationException extends RuntimeException {
public ApplicationException(String message) {
super(message);
}
}
public class ValidationException extends ApplicationException {
public ValidationException(String message) {
super(message);
}
}
Code Explanation:
The provided Java code defines a simple custom exception hierarchy:
Output: When the Main class is run, the createUser method will be called with an empty string. This triggers the ValidationException. The try-catch block will then catch this specific exception.
Validation Error: Username cannot be empty.
If another type of error inheriting from ApplicationException were thrown, and there wasn't a specific catch for it, the more general catch (ApplicationException e) block would handle it. This structure provides both specific and general error-handling capabilities.
How to Answer:
Sample Answer:
How to Answer:
Sample Answer:
Exception handling in Spring Boot REST APIs is crucial for delivering consistent, informative error messages to clients. Use @ExceptionHandler for controller-specific logic, and @RestControllerAdvice (or @ControllerAdvice) for global handling, allowing centralized management of exceptions across all controllers.
This approach wraps exceptions in structured responses (e.g., JSON), includes relevant HTTP status codes, and helps clients understand and resolve issues efficiently. For advanced scenarios, extend ResponseEntityExceptionHandler or implement custom resolvers and error controllers
Code:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse handleResourceNotFound(ResourceNotFoundException ex) {
return new ErrorResponse("Not Found", ex.getMessage());
}
}
Code Explanation: This global exception handler catches all ResourceNotFoundException thrown by any controller and returns a 404 status with a custom error message.
Output Example: The client receives a structured JSON response with clear error information, making it easier to handle errors programmatically.
{
"error": "Not Found",
"message": "Resource was not found"
}
How to Answer:
Sample Answer:
Exception handling is essential for robust applications, but it can impact performance. In Java, creating exception objects, especially with stack traces, is expensive because it gathers and stores detailed execution information. Handling exceptions also disrupts the normal control flow, which can reduce CPU efficiency and slow down execution.
For optimal performance, avoid using exceptions for control flow; instead, use them only for truly exceptional conditions. Prefer unchecked exceptions for business logic and checked exceptions for external API or I/O operations. Logging stack traces should be limited to critical errors to minimize overhead.
How to Answer:
Sample Answer:
Designing a reliable exception handling strategy involves several key steps:
This approach helps ensure the application remains reliable, user-friendly, and easy to maintain.
Example Implementation:
// Special Case Pattern: Handle missing users gracefully
public class UserRepository {
public User findUser(String id) {
User user = fetchFromDB(id);
return (user != null) ? user : new NullUser();
}
}
Code Explanation: This code demonstrates the Special Case Pattern.
Output: Clients receive a NullUser object (with default values) instead of encountering a NullPointerException, ensuring uninterrupted flow.
How to Answer:
Sample Answer:
Code:
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> {
try {
// Simulate error
int result = 10 / 0;
} catch (Exception e) {
// Log and handle exception
System.out.println("Exception in thread: " + e.getMessage());
}
});
Code Explanation:
Output and Explanation:
Exception in thread: / by zero
How to Answer:
Sample Answer:
How to Answer:
Sample Answer:
Code:
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
}
Code Explanation:
Output:
java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:4)
How to Answer:
Sample Answer:
Code Example:
try {
int result = 30 / 0;
} catch (Throwable e) {
System.out.println("Caught: " + e.getClass().getName());
e.printStackTrace();
}
Code Explanation:
This code catches any error or exception (since all are subclasses of Throwable) and prints its class name and stack trace.
Output: The output shows that an ArithmeticException was caught, demonstrating that all exceptions extend from Throwable.
Caught: java.lang.ArithmeticException
java.lang.ArithmeticException: / by zero
at Main.main(Main.java:8)
How to Answer:
Sample Answer:
Technically, exceptions can be ignored by catching them and not taking any action, but this is strongly discouraged. Ignoring exceptions can lead to hidden bugs, inconsistent application state, and unpredictable behavior. In practical scenarios, ignoring exceptions can lead to data corruption, lost transactions, or issues that are difficult to debug.
Best practices include:
Proper exception handling improves application reliability, maintainability, and helps in debugging.
Code Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
// Exception ignored - not recommended
}
Code Explanation:
Output: There is no output or error message displayed.
Since the exception is caught but not handled or reported, the program does not show any indication that an error occurred. This can make it difficult to detect and diagnose problems during development or in production environments.
How to Answer:
Sample Answer:
Global exception handling is essential for maintaining application stability and providing consistent error responses to users or clients.
Best practices for global exception handling include:
These practices help ensure the application is robust, maintainable, and user-friendly, even in the face of unexpected errors.
Code Example:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Code Explanation:
Output: All unhandled exceptions are intercepted and converted into a consistent JSON error response, making it easier for clients to understand and handle errors.
{
"message": "An error occurred: NullPointerException: null",
"status": "INTERNAL_SERVER_ERROR"
}
How to Answer:
Sample Answer:
Follow these simple steps to answer the question:
How to Answer:
Sample Answer:
Sentry, Log4j, and ELK are widely used tools that help teams track exceptions and receive alerts when errors occur.
These tools complement each other:
Code Example:
<!-- Log4j2 configuration for Sentry integration -->
<Configuration status="warn">
<Appenders>
<Sentry name="SentryAppender" dsn="https://examplePublicKey@o0.ingest.sentry.io/0">
<PatternLayout pattern="%m%n"/>
</Sentry>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="SentryAppender"/>
</Root>
</Loggers>
</Configuration>
Code Explanation:
This setup ensures that any exception or error logged in the application is automatically forwarded to Sentry for centralized tracking and alerting.
Output Example:
ERROR [main] Exception in thread "main" java.lang.NullPointerException: null
at com.example.Main.main(Main.java:10)
Exception in thread "main" java.lang.NullPointerException: null
at com.example.Main.main(Main.java:10)
By integrating tools like Sentry with Log4j, the team gains immediate awareness of production issues. Detailed error context enables rapid diagnosis and resolution, while centralized tracking enhances overall application reliability and minimizes downtime.
How to Answer:
Sample Answer:
throw new ExceptionType("Error message");
For example:
throw new IllegalArgumentException("Invalid input value");
Code Example:
public void checkPositive(int number) {
if (number <= 0) {
throw new IllegalArgumentException("Number must be positive.");
}
}
Code Explanation:
Output: When this exception is thrown, it interrupts normal program flow and propagates up to the nearest exception handler. This forces the calling code to either catch and handle the exception or let it propagate further, ensuring that invalid input is not silently ignored.
Exception in thread "main" java.lang.IllegalArgumentException: Number must be positive.
at Example.checkPositive(Example.java:3)
Output Explanation:
With this, we conclude our comprehensive collection of exception handling interview questions and answers customized for both beginners and experienced professionals. Reviewing these will enhance your technical understanding and interview readiness.
Also Read: Introduction to Exception Hierarchy in Java: A Comprehensive Guide
This blog covers top 32 exception handling interview questions and answers, including topics like how to handle exceptions in Java and Python, common exception handling best practices, checked and unchecked exceptions. However, excelling in tech interviews demands more than theoretical knowledge; it requires the ability to effectively apply exception handling principles to scenario-based challenges.
As you take the next step in your journey, consider upGrad's specialized courses. They offer the structured learning, expert guidance, and personalized support needed to bridge skill gaps and accelerate your growth.
Here are a few additional upGrad courses to help you build a strong foundation:
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
Reference:
https://interviewing.io/blog/technical-interview-performance-is-kind-of-arbitrary-heres-the-data
408 articles published
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources