What is the point of the finally block?

后端 未结 16 1111
长情又很酷
长情又很酷 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:56

    Depends on the language as there might be some slight semantic differences, but the idea is that it will execute (almost) always, even if the code in the try block threw an exception.

    In the second example, if the code in the catch block returns or quits, the x = 3 will not be executed. In the first it will.

    In the .NET platform, in some cases the execution of the finally block won't occur: Security Exceptions, Thread suspensions, Computer shut down :), etc.

提交回复
热议问题