Returning from a finally block in Java

前端 未结 6 1988
醉梦人生
醉梦人生 2020-11-22 11:02

I was surprised recently to find that it\'s possible to have a return statement in a finally block in Java.

It seems like lots of people think it\'s a bad thing to d

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 11:47

    Adding control structures and returns to finally{} blocks are just another example of "just because you can" abuses which are scattered throughout virtually all development languages. Jason was right in suggesting it could easily become a maintenance nightmare - the arguments against early returns from functions apply more-so to this case of "late returns".

    Finally blocks exist for one purpose, to allow you to completely tidy up after yourself, no matter what happened in all the preceeding code. Principally this is closing / releasing file pointers, database connections etc., though I could see it being stretched to say adding in bespoke auditing.

    Anything that affects the return of the function should lie in the try{} block. Even if you had a method whereby you checked an external state, did a time consuming operation, then checked that state again in case it became invalid, you would still want the second check inside the try{} - if it sat inside finally{} and the long operation failed, you would then be checking that state a second time needlessly.

提交回复
热议问题