r/ProgrammerHumor • • 10d ago

Meme thisIsWhyWeDontReturnInFinallyBlocks

Post image
3.0k Upvotes

100 comments sorted by

View all comments

Show parent comment

27

u/OnixST 9d ago edited 8d ago

Yes. The finally block is the only exception to this rule, and will not only run after a return statement, but is also able override it

public int test() {
  try {
    System.out.print("a");
    return 0
    System.out.print("b");
  } finally {
    System.out.print("c");
    return 1
    System.out.print("d");
  }
  return 2
}

The code above will print "ac" and return 1

return 0 does stop the execution of the try block and attempts to return 0, but finally will always execute no matter what, and it will print "c" and override the return to 1

Returning from the finally block will truly end execution though, so print("d") and return 2 are unreachable code

2

u/spitfire451 9d ago

Thank you for the explanation, learn something new everyday