Java Interview Questions – Exception Handling & Error Management
1. [Amazon] What happens if an exception is thrown in a catch block?
Answer: If an exception is thrown in a catch block, it propagates normally unless caught by another try-catch.
2. [Google] What is the difference between throw and throws in Java?
Answer:
- throw: Used to explicitly throw an exception.
- throws: Declares exceptions a method might throw.
3. [Microsoft] What is the purpose of multi-catch in Java?
Answer: Multi-catch (catch(Exception1 | Exception2 e)) allows a single catch block to handle multiple exception types.
4. [Netflix] What is the difference between checked and unchecked exceptions?
Answer:
- Checked exceptions (e.g., IOException) must be handled at compile-time.
- Unchecked exceptions (e.g., NullPointerException) occur at runtime.
5. [Facebook] What happens if you throw an exception in a finally block?
Answer: If an exception is thrown inside finally, it overrides any previous exceptions thrown in try or catch.
6. [Oracle] What is the try-with-resources statement in Java?
Answer: It automatically closes resources like files and sockets to prevent memory leaks.
7. [Uber] How can we create a custom exception in Java?
Answer: By extending the Exception class for checked exceptions or RuntimeException for unchecked exceptions.
8. [Deloitte] Can we handle multiple exceptions in a single catch block?
Answer: Yes, using the multi-catch syntax (catch(Exception1 | Exception2 e)).
9. [JP Morgan] What is the purpose of the Error class in Java?
Answer: The Error class represents serious issues (e.g., OutOfMemoryError) that applications usually cannot recover from.
10. [Goldman Sachs] What is the difference between AssertionError and Exception?
Answer:
- AssertionError: Thrown when an assert statement fails.
- Exception: Represents general runtime issues.
