Java - Finally Block-interview
Q1. What is the purpose of the finally block in Java?
The finally block is used to place important code that must execute regardless of whether an exception occurs, such as resource cleanup (closing files, releasing DB connections).
Q2. Does the finally block always execute?
Yes, the finally block executes in almost all cases, except when the JVM exits using System.exit() or the program crashes due to a fatal error.
Q3. Can a finally block be used without a catch block?
Yes. A finally block can be used with a try block even without catch. In such cases, it still executes after the try block finishes.
Q4. What happens if an exception is thrown inside the finally block?
If an exception occurs in the finally block, it can override an exception thrown in the try or catch block, leading to unexpected behavior. Best practice: avoid risky code in finally.
Q5. What is the difference between final, finally, and finalize in Java?
- final: Keyword used for constants, preventing inheritance/overriding.
- finally: Block used in exception handling for cleanup code.
- finalize(): Method called by garbage collector before object destruction (deprecated in newer Java versions).