What is the point of the finally block?

后端 未结 16 1224
长情又很酷
长情又很酷 2020-12-30 20:19

Syntax aside, what is the difference between

try {
}
catch() {
}
finally {
    x = 3;
}

and

try {
}
catch() {
}

x = 3;
         


        
16条回答
  •  清歌不尽
    2020-12-30 20:51

    This question is old, but this has always bothered me (I found it here for a reason). I've read every answer and it looks to me that nobody really thought it through.

    This is not an answer. I really think there is no good point to finally, which may be why it didn't exist in programming languages until "recently". Most of the examples stating stream.close() can cause null reference exceptions, so you still have to test if it's null.

    Yes, if you return from within try{}, finally still runs. But is that good practice? It seems like gynastics, might as well bring goto back. Why not wait and return after the block? All finally {} does is add two or three lines to your code.

提交回复
热议问题