What is the point of the finally block?

后端 未结 16 1211
长情又很酷
长情又很酷 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 21:14

    try catch finally is pretty important construct. You can be sure that even if an exception is thrown, the code in finally block will be executed. It's very important in handling external resources to release them. Garbage collection won't do that for you. In finally part you shouldn't have return statements or throw exceptions. It's possible to do that, but it's a bad practice and can lead to unpredictable results.

    If you try this example:

    try {
      return 0;
    } finally {
      return 2;
    }
    

    The result will be 2:)

    Comparison to other languages: Return From Finally

提交回复
热议问题