Exception Handling Interview Questions
Checked exceptions are verified by the compiler at compile-time and must be either handled or declared using throws. Unchecked exceptions extend RuntimeException and are not checked by the compiler.
Q1. What is the difference between checked and unchecked exceptions? Checked exceptions are verified by the compiler at compile-time and must be either handled or declared using throws. Unchecked exceptions extend RuntimeException and are not checked by the compiler.
Q2. What is the difference between `throw` and `throws`? throw is used inside a method to actually trigger a specific exception object. throws is used in a method's signature to declare that the method might produce a certain type of exception.
Q3. Does the `finally` block always execute? Yes, finally executes whether or not an exception occurred, and even if the try block contains a return statement (with rare exceptions, like if the JVM itself shuts down abruptly).
Q4. Can you have a try block without a catch block? Yes, as long as it has a finally block. A try block must be followed by at least one catch, or a finally, or both.
Q5. What is a custom exception, and why would you create one? A custom exception is a user-defined exception class, usually extending Exception or RuntimeException, created to represent a specific error condition relevant to your application's own business logic more clearly than a generic built-in exception would.
Q6. What happens if an exception is thrown but never caught? The program terminates abruptly, and the JVM prints a stack trace describing the exception and where it occurred.
Key Points to Remember
- Interviewers often ask you to trace through code involving nested try-catch-finally blocks — practice this carefully.
- Understand exactly when
finallyruns, even with earlyreturnstatements insidetryorcatch. - Be ready to explain real scenarios where you'd create a custom exception in a real project.