What's the point of the "finally" block? Isn't it functionally equivalent to everything after the try { } clause?

  • 19
    No, not really. A finally clause is always executed, even if an exception is not handled in a catch clause. The code after the try would not be executed in that case.
  • 6
    If try or catch block throws exception, then it is not equivalent to the code appearing after the try block

    Think of it like a cleanup block to tear down anything that might have been tried
  • 5
    Ok I didn't know that thanks
  • 6
    Save for a hard crash, forcibly exiting the application, etc. you have an iron clad guarantee that the finally block in question will *always* run (even if you return from the method in the try block, or an unhandled exception is thrown in the try block.
  • 1
    Others explained it but for uses I can think of

    - releasing a mutex lock or similar
    - properly closing file streams or network sockets
    - making a backup save of the users data so it won't be lost in case of a full crash
Add Comment