Java Interview Questions

Previous Java Interview Questions Next

Java Exception Handling - Theory Questions

1. What is an exception in Java and what is exception handling?

An exception is an event that disrupts the normal flow of program execution. It's an object that wraps an error event occurred within a method. Exception handling is a mechanism to handle runtime errors gracefully, allowing the program to continue execution or terminate smoothly. Java provides try-catch blocks, throw, throws, and finally keywords to implement exception handling, ensuring robust and fault-tolerant applications.

2. What is the difference between checked and unchecked exceptions?

Checked exceptions are checked at compile-time. They must be either caught or declared in the method signature using throws clause (e.g., IOException, SQLException). Unchecked exceptions are not checked at compile-time and occur at runtime (e.g., NullPointerException, ArrayIndexOutOfBoundsException). Checked exceptions represent scenarios outside program control, while unchecked exceptions represent programming errors that should be fixed in code.

3. Explain the exception hierarchy in Java.

The Java exception hierarchy starts with Throwable class at the top. It has two main subclasses: Exception and Error. Exception class has further subclasses: RuntimeException (unchecked exceptions) and other exceptions (checked exceptions). Error class represents serious system problems that applications should not try to catch (e.g., OutOfMemoryError, StackOverflowError). All user-defined exceptions should extend Exception or RuntimeException.

4. What are the keywords used in exception handling and their purposes?

Key exception handling keywords: try - defines a block of code to be tested for errors, catch - defines a block to handle specific exceptions, finally - defines code that always executes (for cleanup), throw - used to explicitly throw an exception, and throws - declares exceptions that a method might throw. These keywords work together to provide comprehensive exception handling mechanism.

5. What is the difference between throw and throws keywords?

throw is used to explicitly throw an exception instance within a method. It's followed by an exception object. throws is used in method signature to declare that a method might throw certain exceptions. It's followed by exception class names. Throw is used to actually generate an exception, while throws is used to warn callers about potential exceptions they need to handle.

6. Explain the try-catch-finally block with examples.

The try block contains code that might throw exceptions. Catch block(s) handle specific exceptions. Finally block always executes regardless of whether an exception occurred. Example:
try { riskyOperation(); }
catch (IOException e) { handleIOError(e); }
finally { cleanupResources(); }

The finally block is ideal for resource cleanup like closing files, database connections, etc.

7. What is the purpose of the finally block?

The finally block is used for cleanup code that must execute regardless of whether an exception occurs. It always executes when the try block exits, even if: No exception occurs, An exception occurs and is caught, An exception occurs and is not caught, or A return statement is executed in try/catch. This makes it perfect for releasing resources like file handles, database connections, network connections, or any cleanup operations.

8. Can we have a try block without catch or finally?

No, a try block must be followed by either at least one catch block or a finally block. However, with Java 7, you can use try-with-resources statement which doesn't require explicit catch or finally blocks for resource management. The syntax requires either catch blocks, finally block, or both. A try block alone will result in compilation error.

9. What is multiple catch blocks and how does it work?

Multiple catch blocks allow handling different types of exceptions differently. When an exception occurs in try block, catch blocks are checked in order for a matching exception type. Important rules: More specific exception catch blocks must come before more general ones, and Only one catch block executes for any exception. From Java 7, you can use multi-catch: catch (IOException | SQLException e) to handle multiple exceptions in one block.

10. What is exception propagation in Java?

Exception propagation is the process where an exception is passed from the method where it occurs up through the call stack until it's caught or reaches the top. If a method doesn't handle an exception, it's automatically propagated to the calling method. This continues until the exception is caught or the program terminates. Checked exceptions must be declared in the method signature using throws if not handled locally.

11. What are custom exceptions and when should we use them?

Custom exceptions are user-defined exception classes that extend either Exception (checked) or RuntimeException (unchecked). They should be used when: You need exception types specific to your application domain, You want to add custom information or behavior to exceptions, or Standard Java exceptions don't adequately describe the error scenario. Custom exceptions make error handling more meaningful and application-specific.

12. What is the difference between final, finally, and finalize?

final is a keyword used for constants, non-inheritable classes, and non-overridable methods. finally is a block in exception handling that always executes. finalize is a method in Object class called by garbage collector before object destruction. They serve completely different purposes: final for immutability/inheritance control, finally for cleanup, and finalize for resource cleanup before garbage collection (deprecated in Java 9).

13. What is try-with-resources introduced in Java 7?

Try-with-resources is a feature introduced in Java 7 that automatically closes resources that implement AutoCloseable interface. Syntax: try (ResourceType resource = new ResourceType()) { // use resource }. The resource is automatically closed at the end of the try block, even if an exception occurs. This eliminates the need for explicit finally blocks for resource cleanup and reduces boilerplate code. It also suppresses exceptions thrown during close() operation.

14. What is exception chaining and how is it achieved?

Exception chaining is the process of wrapping one exception inside another to preserve the original exception context. It's achieved by: Passing the original exception as a parameter to the new exception constructor, or Using initCause() method. This allows tracking the complete exception history. Example: throw new DatabaseException("Connection failed", originalException);. Chaining helps in debugging by maintaining the complete stack trace.

15. What are the best practices for exception handling?

Best practices include: Be specific in catch blocks, Don't ignore exceptions (empty catch blocks), Use checked exceptions for recoverable conditions, Use unchecked exceptions for programming errors, Close resources in finally blocks or use try-with-resources, Document exceptions with Javadoc, Don't expose implementation details in exception messages, and Use custom exceptions for business logic errors.

16. What is the difference between Error and Exception?

Error indicates serious problems that a reasonable application should not try to catch (e.g., OutOfMemoryError, VirtualMachineError). They are unchecked and represent system-level problems. Exception indicates conditions that a reasonable application might want to catch. They can be checked or unchecked and represent application-level problems. Errors are typically beyond the control of the application, while exceptions can often be handled programmatically.

17. Can we write try block inside catch or finally block?

Yes, you can nest try blocks inside catch or finally blocks. This is called nested exception handling. However, it should be used judiciously as it can make code complex and hard to read. Nested try blocks are useful when you need to handle exceptions that might occur during exception handling itself, or when performing cleanup operations in finally that might themselves throw exceptions.

18. What is the return type of a method when exception is thrown?

When a method throws an exception, it doesn't return normally. The method execution is interrupted, and control transfers to the appropriate catch block in the call stack. If the exception is not caught, the method terminates abruptly. The return type declaration in method signature remains unchanged - exceptions are separate from return types. However, if a return statement is in finally block, it overrides any return in try or catch blocks.

19. What are suppressed exceptions in try-with-resources?

In try-with-resources, if both the try block and the automatic close() operation throw exceptions, the exception from the try block is propagated, and the exception from close() is suppressed. These suppressed exceptions can be retrieved using getSuppressed() method on the primary exception. This prevents losing important exception information while maintaining a clean exception propagation model.

20. How does exception handling affect performance?

Exception handling has some performance considerations: Creating exception objects is expensive due to stack trace generation, Exception handling should not be used for normal control flow, Using exceptions for expected conditions can degrade performance, However, in modern JVMs, the cost is acceptable for exceptional conditions. The key is to use exceptions only for truly exceptional situations, not for regular program logic.

Previous Java Interview Questions Next