CTA
Whether you are an experienced developer or a fresher candidate appearing for SDE interviews, chances are the interviewer will throw tricky exception-handling questions at you to test your programming knowledge. That is why it is immensely critical to try your hands at mitigating exceptions and practicing coding implementation of the same. After doing a careful analysis of critical exception-handling concepts, we have curated the list of 50 Java exception-handling interview questions that are commonly asked in the SDE interviews. This list of questions is endorsed by the hiring partners associated with us, so ensure that you prepare for them thoughtfully!
Basic Exception Handling Interview Questions for Freshers
1. What is an exception in Java?
An exception is an event that disrupts the normal flow of a program’s instructions during execution. It indicates that something unexpected has occurred. Exceptions can be caused by various factors, such as invalid user input, hardware failures, or programming errors. When an exception occurs, it can be handled by the program to prevent it from crashing, or it can be allowed to propagate upward through the call stack.
2. What are runtime exceptions in Java?
Runtime exceptions, also known as unchecked exceptions, are exceptions that occur during the execution of a program. The compiler does not check them at compile time, hence the term “unchecked”. Runtime exceptions usually arise from logical errors in the program’s code and are not typically caused by external factors like input/output failures. Examples include NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.
Here’s an example code with the respective outcome:
public class ArrayIndexOutOfBoundsExample {
public static void main(String[] args) {
// Initialize an array with 3 elements
int[] numbers = {1, 2, 3};
try {
// Try to access the 4th element (index 3)
System.out.println("The fourth element is: " + numbers[3]);
} catch (ArrayIndexOutOfBoundsException e) {
// Handle the exception
System.out.println("Exception caught: " + e);
}
System.out.println("Program continues...");
}
}
3. Differentiate between checked exceptions and unchecked exception in Java.
Feature |
Checked Exception |
Unchecked Exception |
Definition |
Exceptions checked by the compiler at compile time |
Exceptions not checked by the compiler at compile time |
Handling Requirement |
Must be handled using try-catch blocks or declared with throws |
No requirement to handle or declare |
When They Occur |
Compile time |
Runtime |
Cause |
Can be anticipated and recovered from |
Typically caused by programming errors (logic mistakes) |
Examples |
IOException, ClassNotFoundException |
NullPointerException, ArrayIndexOutOfBoundsException |
4. What is exception handling in Java, and what are the advantages of exception handling?
Exception handling in Java is a mechanism to handle runtime errors, allowing the program to continue its normal flow. Java provides a robust framework for handling exceptions using five keywords: try, catch, finally, throw, and throws.
try: The block of code where exceptions might occur.
catch: The block of code that handles the exception.
finally: The block of code that executes regardless of whether an exception occurs.
throw: Used to throw an exception explicitly.
throws: Indicates what exceptions a method can throw.
Some advantages of exception handling include:
- Separation of error-handling code
- Propagating errors up the call stack
- Grouping and differentiating error types
- Resource management
- Improved program reliability
- Enhanced debugging capabilities
5. How are exceptions handled in Java?
Exceptions in Java are handled using a combination of try, catch, and finally blocks. The code that may potentially throw an exception is enclosed within a try block. If an exception occurs within the try block, it is caught by one or more catch blocks that handle specific types of exceptions.
The finally block, if present, is executed regardless of whether an exception occurs. It is commonly used to release resources such as file handles or database connections.
6. How do you handle checked exceptions?
Checked exceptions in Java must be either caught using a try-catch block or declared in the method signature using the throws keyword.
When using a try-catch block, the code that may throw the checked exception is enclosed within a try block, and the catch block catches the exception and handles it appropriately.
If the checked exception is not caught within the method, it must be declared in the method signature using the throws keyword. This informs the caller of the method that the exception may occur and must be handled by the caller.
7. What is the difference between the throw and throws keywords in Java?
Keyword |
Usage |
Context |
throw |
Used to explicitly throw an exception within a method. It is followed by an instance of the Throwable class or one of its subclasses. |
Throwing exceptions |
throws |
Used in the method signature to declare the exceptions that a method might throw. It specifies the types of exceptions that must be handled by the caller or propagated up the call stack. |
Declaring exceptions in a method signature |
8. Can we have statements between try, catch, and finally blocks?
No, you cannot have statements between the “try”, “catch”, and “finally” blocks in Java. These blocks must be part of a single, cohesive structure without any intervening statements.
If you try to place any statements between these blocks, the code will not compile and result in a syntax error. Each try block must be immediately followed by one or more catch blocks, and optionally, a finally block, with no statements in between.
9. How are the keywords final, finally, and finalize different from each other?
-
- Variables: When a variable is declared as final, its value cannot be changed once it is initialized.
- Methods: When a method is declared as final, it cannot be overridden by subclasses.
- Classes: When a class is declared as final, it cannot be subclassed.
-
- Purpose: To ensure that a block of code is executed no matter what happens in the try block, typically for resource cleanup.
- Use Case: Closing files, releasing resources, etc.
-
- Purpose: To perform cleanup operations before an object is garbage collected.
- Usage: Rarely used in modern Java programming due to unpredictability and performance issues. Recommended to use try-with-resources and other resource management techniques instead.
These keywords serve different purposes and should be used appropriately depending on the specific needs of your Java programs.
10. What are the benefits of using try-with-resources?
The key advantage of try-with-resources is that it prevents resource leaks, which could occur if we do not correctly close the resources after use. Try-with-resources also offers the advantage of improving code readability by eliminating superfluous statements.
Get 100% Hike!
Master Most in Demand Skills Now!
11. What is a stack trace and how is it related to an exception?
A stack trace is a list of method calls from the point of an exception occurrence to the program’s entry point. It includes the exception type, message, line numbers, and file names where each method was called.
Stack traces help developers diagnose errors by revealing the sequence of method invocations that led to the exception, aiding in debugging and troubleshooting. They are crucial for identifying and resolving runtime errors and exceptions in Java programs.
12. What is a nested try-catch block?
A try-catch block inside another try-catch block is known as a nested try-catch block. An exception in the inner block can be caught and handled independently from exceptions in the outer block, enabling more precise error management. This is helpful for managing various error kinds at various program levels.
Here’s a code for the same:
public class NestedTryCatchDemo {
public static void main(String[] args) {
try {
// Outer try block
System.out.println("Outer try block started.");
try {
// Inner try block
System.out.println("Inner try block started.");
int result = 10 / 0; // This will throw ArithmeticException
System.out.println("Inner try block ended."); // This won't be executed
} catch (ArithmeticException e) {
// Inner catch block
System.out.println("Caught ArithmeticException in inner catch: " + e);
}
System.out.println("Outer try block continues.");
String str = null;
System.out.println(str.length()); // This will throw NullPointerException
} catch (NullPointerException e) {
// Outer catch block
System.out.println("Caught NullPointerException in outer catch: " + e);
}
System.out.println("Program continues...");
}
}
Output:
Explanation:
- Outer Try Block: Contains the main code that might throw an exception.
- Inner Try Block: Nested inside the outer try block and handles its own specific exceptions.
- Inner Catch Block: Catches and handles exceptions thrown within the inner try block.
- Outer Catch Block: Catches and handles exceptions thrown within the outer try block that are not handled by the inner catch block.
13. What are the important methods defined in Java’s Exception Class?
Java’s “Exception” class, a superclass of all checked exceptions, provides several important methods for handling and working with exceptions. These methods are essential for diagnosing, logging, and handling exceptions in Java programs.
- getMessage(): Retrieves the error message associated with the exception.
- getCause(): Returns the cause of the exception or “null” if the cause is unknown.
- printStackTrace(): Prints the stack trace of the exception to the standard error stream.
- toString(): Returns a string representation of the exception, typically containing the class name and error message.
- getStackTrace(): Returns an array of “StackTraceElement” objects representing the stack trace elements.
14. What is the difference between ClassNotFoundException and NoClassDefFoundError?
The ClassNotFoundException indicates that a class definition could not be found during runtime, while NoClassDefFoundError indicates that a class definition that was available during compilation is missing during runtime.
15. What do you understand by an unreachable catch block error?
In simple terms, an “unreachable catch block” error in Java happens when the compiler finds that a catch block won’t ever catch any exceptions. This can occur if another catch block already catches all possible exceptions or if the type of exception in the catch block doesn’t match any exceptions that can be thrown in the try block. This error stops the code from compiling because it suggests that the exception handling setup won’t work properly.
Intermediate Exception Handling Interview Questions
16. Explain the concept of exception handling in the context of method overriding. What are the rules regarding exceptions in overridden methods?
Exception handling in the context of method overriding refers to how exceptions are managed when a subclass provides a specific implementation for a method that is already defined in its superclass. In Java, when a method is overridden, certain rules govern how exceptions can be thrown by the overriding method compared to the method in the superclass.
Here are the key rules regarding exceptions in overridden methods:
- Checked Exceptions: The overriding method can only throw exceptions that are the same as or a subset of the exceptions declared in the throws clause of the method in the superclass. It cannot throw new or broader checked exceptions.
- Unchecked Exceptions: The overriding method can throw any unchecked exceptions (runtime exceptions), regardless of whether the superclass method declares them or not.
- No Exceptions: If the superclass method does not declare any exceptions, the overriding method in the subclass can still throw unchecked exceptions but cannot throw any checked exceptions.
- Exception Specification in Interfaces: When overriding methods specified in an interface, the same rules apply. The implementation can throw the same or fewer checked exceptions as declared in the interface method, and it can throw any unchecked exceptions.
- Constructors: Constructors do not follow the same rules as methods. Each constructor in the subclass can declare its own set of exceptions independently of the superclass constructors.
17. What is the purpose of the “try-with-resources” statement, and how does it differ from a regular “try-catch” block?
The purpose of the “try-with-resources” statement in Java is to ensure that resources like files, database connections, and sockets are automatically closed after use, preventing resource leaks. Introduced in Java 7, it simplifies resource management by closing each resource at the end of the statement, whether the try block completes normally or due to an exception. This is achieved by having the resources implement the “AutoCloseable” interface.
In contrast, a regular “try-catch” block requires explicit resource closure, typically in a finally block, to avoid leaks. This manual management can lead to more verbose and error-prone code. The try-with-resources statement thus enhances code readability, reduces boilerplate, and ensures safer and cleaner handling of resources.
18. What happens if we have statements after the finally block and the control is returning from the finally block itself?
If there are statements after the finally block and the control returns from the finally block itself, those statements after the finally block will not be executed. This is because the finally block is designed to execute regardless of whether an exception is thrown, but if a “return”, “break”, or “continue” statement is encountered within the finally block, it will exit the method or loop immediately, bypassing any subsequent code.
Example:
public void exampleMethod() {
try {
// Some code
} catch (Exception e) {
// Handle exception
} finally {
return; // Exiting the method here
}
// This code will never be executed
System.out.println("This will not be printed.");
}
When control exits from the “finally” block using a “return” statement, any code following the “finally” block is skipped, and the method exits immediately.
19. What do you mean by ClassCastException?
“ClassCastException” is a runtime exception in Java that occurs when an object is forcibly cast to a type to which it is not compatible. This exception is thrown to signal that the code has attempted to cast an object to a subclass of which it is not an instance.
For example, consider the following code:
Object obj = new Integer(10);
String str = (String) obj; // This line will throw ClassCastException
In this example, the “Object” reference “obj” actually points to an “Integer” object, but the code attempts to cast it to a “String”, resulting in a “ClassCastException”.
The exception can be avoided by using the “instanceof” operator to check the type before casting:
if (obj instanceof String) {
String str = (String) obj;
}
Proper type checking ensures that casting is only performed when it is safe, thereby preventing this exception.
20. What does JVM do when an exception occurs in a program?
- When an error happens in a Java program, the Java Virtual Machine (JVM) makes an “Exception” object that represents the error. The JVM looks for a matching catch block in the current method to handle the error.
- If it doesn’t find one, the method stops running, and the JVM passes the exception to the method that called it. This continues until it finds a matching catch block.
- If no matching catch block is found anywhere, the JVM uses its default handler, which prints the error details and stops the program.
- The printed details include the type of error, a message about the error, and a list of methods that were called, which helps developers understand what went wrong.
21. What is exception propagation?
Exception propagation is the process by which an exception is passed up the call stack from the point where it was thrown to the point where it is caught and handled. When an exception occurs in a method and is not caught within that method, it is propagated, or “thrown,” to the calling method.
For example, if Method A calls Method B and Method B calls Method C where an exception occurs, but Method C does not handle it, the exception is propagated back to Method B. If Method B also does not handle it, the exception is further propagated to Method A. If none of these methods handle the exception, it ultimately causes the program to terminate and print an error message.
Exception propagation allows methods to defer error handling to higher-level methods, which can provide a centralized place for managing exceptions and implementing appropriate recovery or logging mechanisms.
22. Explain user-defined exceptions. Give an example.
User-defined exceptions, also known as custom exceptions, allow developers to create their exception types tailored to specific situations in their applications. These exceptions extend built-in exception classes or implement the “Throwable” interface, enabling developers to define custom error messages, error codes, and behavior.
Example:
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
class BankAccount {
private int balance = 0;
public void withdraw(int amount) throws CustomException {
if (amount > balance) {
throw new CustomException("Insufficient funds");
}
balance -= amount;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
try {
account.withdraw(100);
} catch (CustomException e) {
System.out.println(e.getMessage()); // Output: Insufficient funds
}
}
}
In this example, CustomException is a user-defined exception that extends the built-in Exception class. The “BankAccount” class uses this custom exception to handle cases where a withdrawal amount exceeds the available balance. When such a situation occurs, a “CustomException” instance is thrown with a custom error message indicating the reason for the exception.
23. What is a chained exception in Java?
In Java, a chained exception, also known as a nested or wrapped exception, occurs when one exception is thrown in response to another exception. It allows developers to preserve the context and cause of an exception by associating it with another exception.
When an exception is thrown and caught, it can be rethrown with a different exception as its cause, creating a chain of exceptions. This can provide more detailed information about the root cause of an error, helping developers diagnose and debug issues more effectively.
24. What are the methods provided by the Throwable class in Java?
The Throwable class is the superclass of all errors and exceptions in the Java language. It provides several methods that allow you to interact with and retrieve information about exceptions and errors. Here are some of the key methods provided by the Throwable class:
- getMessage(): Returns a detailed message string of the throwable, which can provide information about the cause of the exception.
- getLocalizedMessage(): Returns a localized description of the throwable. Subclasses can override this method to return a locale-specific message.
- getCause(): Returns the cause of the throwable (the exception that caused this throwable to be thrown), or null if the cause is not set.
- initCause(Throwable cause): Initializes the cause of the throwable. This method can only be called once and is typically used when an exception is constructed.
- printStackTrace(): Prints the throwable and its backtrace to the standard error stream.
- printStackTrace(PrintStream s): Prints the throwable and its backtrace to the specified PrintStream.
- printStackTrace(PrintWriter s): Prints the throwable and its backtrace to the specified PrintWriter.
- fillInStackTrace(): Fills in the execution stack trace. This method records within this Throwable object information about the current state of the stack frames for the current thread.
- getStackTrace(): Returns an array of StackTraceElement objects representing the stack trace of the throwable.
- setStackTrace(StackTraceElement[] stackTrace): Sets the stack trace elements that will be returned by getStackTrace() and printed by printStackTrace().
- addSuppressed(Throwable exception): Adds a throwable to the list of suppressed exceptions. This is useful when a secondary exception is thrown in a finally block.
- getSuppressed(): Returns an array of Throwable objects representing the exceptions that were suppressed to deliver this exception.
25. It is always recommended to close the DB resources to keep them inside a finally block. Why?
Closing database resources in a “finally” block ensures that the resources are released regardless of whether an exception occurs. This prevents resource leaks, which can lead to performance issues and exhaustion of database connections, ensuring better resource management and application stability.
Advanced Exception Handling Interview Questions for Experienced
26. Can you explain the Java exception hierarchy?
The Java exception hierarchy is a structured framework that categorizes various types of errors and exceptions that can occur during the execution of a program.
At the top of this hierarchy is the “Throwable” class, which has two main subclasses: “Error” and “Exception”. Error represents serious issues that typically cannot be handled by the application, such as “OutOfMemoryError” or “StackOverflowError”.
The Exception class, on the other hand, is divided into checked and unchecked exceptions. Checked exceptions, which extend Exception directly (e.g., IOException and SQLException), must be declared in a method’s `throws` clause and handled by the programmer.
Unchecked exceptions, which are subclasses of RuntimeException (e.g., NullPointerException, ArrayIndexOutOfBoundsException), do not require explicit handling and often indicate programming errors. This hierarchy allows developers to write robust and error-resistant code by distinguishing between recoverable conditions and serious application errors.
27. What actions does the JVM take when an exception occurs in a program?
When an exception occurs in a Java program, the JVM (Java Virtual Machine) takes several actions to handle the exception:
- Exception Object Creation: When an exception is thrown, an exception object is created. This object contains information about the type of exception, the stack trace, and other relevant details.
- Exception Propagation: The JVM searches for a suitable exception handler to handle the exception. It checks the call stack to find a method with a matching “try-catch” block that can handle the exception.
- Stack Unwinding: If an appropriate “catch” block is found to handle the exception, the JVM begins unwinding the call stack. It starts by unwinding the stack frame by frame, popping off method calls until it reaches the method with the matching “catch” block.
- Exception Handling: Once the appropriate “catch” block is found, the JVM executes the code within that block to handle the exception. The code in the “catch” block may perform error recovery, logging, or other actions to deal with the exceptional condition.
28. What is the outcome when an exception is thrown by the main method?
When an exception is thrown by the main method in a Java program and it is not caught and handled within the main method itself, the JVM takes the following actions:
Exception Propagation: The JVM searches for a suitable exception handler to handle the exception. It checks the call stack to find any method that may have a matching `try-catch` block to handle the exception.
Propagation Beyond main: If no suitable try-catch block is found within the main method or any methods it calls, the exception propagates beyond the main method up the call stack to the JVM itself.
Termination of the Program: Since there is no handler for the exception, the JVM terminates the program and prints the exception details to the console. This includes the exception type, message, and stack trace, which help developers diagnose and debug the issue.
29. In what scenarios could an
An “Exception in thread main error” can occur in various scenarios, including:
- Unchecked Exceptions: If the main method or any method it calls throws an unchecked exception and it is not caught and handled within the main method or its callers, the JVM will terminate the program with an “Exception in thread main” error.
- Checked Exceptions: If the main method or any method it calls throws a checked exception and it is not caught and handled within the main method or its callers, the JVM will terminate the program with an “Exception in thread main” error.
- Resource Management Issues: If there are issues related to resource management, such as failure to close resources properly (e.g., file handles, database connections) within the main method or its callers, it might lead to unchecked or checked exceptions, resulting in the error.
- Error Conditions: Certain error conditions, such as “OutOfMemoryError” or “StackOverflowError”, occurring within the main method or its callers, can also result in an “Exception in thread main” error and termination of the program.
- Invalid Program State: If there are logical errors or invalid states in the program that lead to unexpected behavior or exceptions during the execution of the main method or its callers, it can result in an “Exception in thread main error”.
30. Is it permissible to use only try blocks without accompanying catch or finally blocks?
Yes, it is permissible to use a try block without accompanying catch or finally blocks in Java. This construct is known as a “try-with-resources” statement and is used specifically for automatic resource management. In a try-with-resources statement, you declare one or more resources within the parentheses of the “try” statement.
Here’s the basic syntax of a try-with-resources statement:
try (ResourceType resource1 = new ResourceType(); ResourceType resource2 = new ResourceType()) {
// Use the resources
} // Resources are automatically closed here
In this construct, you only use the try block to manage resources, and you don’t need to include catch or finally blocks. If an exception occurs within the try block, the resources are still automatically closed before the exception is propagated.
31. Can exceptions be thrown inside the body of a lambda expression?
Yes, exceptions can be thrown inside the body of a lambda expression in Java. Here’s an example demonstrating throwing an unchecked exception within a lambda expression:
// Functional interface
interface MyFunctionalInterface {
void myMethod();
}
public class Main {
public static void main(String[] args) {
// Lambda expression throwing unchecked exception
MyFunctionalInterface myLambda = () -> {
throw new RuntimeException("Unchecked exception thrown in lambda");
};
// Calling the lambda expression
myLambda.myMethod();
}
}
In the example above, the lambda expression within “myLambda” throws a “RuntimeException”, which is an unchecked exception. Since unchecked exceptions do not need to be caught or declared, this code compiles and runs without error.
32. Is it possible to throw checked exceptions from a static block?
Yes, it is possible to throw checked exceptions from a static block in Java. Here’s an example demonstrating throwing a checked exception from a static block:
public class MyClass {
static {
try {
// Code that may throw a checked exception
throw new IOException("Checked exception thrown from static block");
} catch (IOException e) {
// Handle the exception or rethrow it
e.printStackTrace();
}
}
// Other class members and methods
}
In this example, the static block of the “MyClass” class throws an “IOException”, which is a checked exception. It catches the exception and handles it by printing the stack trace. Alternatively, the exception could be rethrown, but it would need to be caught or declared by the method or constructor that uses the class “MyClass”.
33. When should we consider subclassing an exception?
Subclassing an exception in Java is considered when you want to create custom exception types that convey specific information about exceptional conditions in your application. Here are some scenarios where subclassing an exception is appropriate:
- Domain-Specific Exceptions: Create custom exceptions tailored to specific operations, like “PaymentFailedException” for payment processing errors.
- Enhanced Error Information: Provide extra context or details with custom fields, error codes, or messages to aid debugging.
- Granular Exception Handling: Handle different errors differently based on specific exception types, allowing targeted recovery strategies.
- API Design: Improve API clarity by defining custom exception types, making error handling more intuitive for API users.
- Encapsulation: Keep error-handling logic separate from application logic by encapsulating it within custom exception types.
- Consistency and Reusability: Define a hierarchy of custom exceptions for consistent error representation and reuse across the application.
34. What rules should be followed when overriding a method that throws an exception?
By adhering to the following rules, you can ensure proper exception handling and compatibility when overriding methods in Java.
- Same or Subtype Exception: Ensure that the overridden method either throws the same type of exception as the superclass method or a subtype of it. This maintains compatibility with the superclass method’s exception signature.
- No New Checked Exceptions: Avoid introducing new checked exceptions in the overridden method that are not declared by the superclass method. Doing so violates the principle of method contract inheritance and can cause compilation errors.
- Unchecked Exception: The overridden method is free to throw unchecked exceptions without declaring them in the method signature. Unchecked exceptions can be thrown freely.
- Use “@Override” Annotation: Always use the “@Override” annotation when overriding a method to ensure that you are indeed overriding a method from a superclass. This helps catch errors at compile time if the method signature doesn’t match any method in the superclass.
35. What are some best practices for handling exceptions in Java?
Here are some best practices for handling exceptions in Java. By following these best practices, you can improve the reliability, maintainability, and readability of your Java code when handling exceptions.
- Use Specific Exceptions: Catch specific exceptions rather than using generic “Exception” catch blocks. This allows for more targeted error handling and clearer code.
- Log Exceptions: Always log exceptions or error messages when they occur. This helps in debugging and troubleshooting issues in production environments.
- Resource Management: Use try-with-resources statements for automatic resource management. This ensures that resources are properly closed, even in the event of an exception.
- Use Finally Blocks for Cleanup: Use “finally” blocks to perform cleanup actions, such as closing resources, regardless of whether an exception occurs.
- Follow Exception Propagation: Let exceptions propagate up the call stack to higher-level code that can handle them appropriately. Avoid catching exceptions too low in the call stack if they should be handled higher up.
- Use Custom Exceptions: Create custom exception types for specific error conditions in your application. This allows for more meaningful error messages and better error handling.
- Use Checked Exceptions Judiciously: Use checked exceptions only for exceptional conditions that the caller can reasonably be expected to handle. Avoid excessive use of checked exceptions, as they can clutter code and impose an unnecessary burden on callers.
We hope these Java exception-handling interview questions will help you prepare for your interviews. All the best! Enroll today in our comprehensive Core Java course or join Intellipaat’s Java Certification Training Course, to start your career or enhance your skills in the field of data science and get certified today.