What is the point of the finally block?

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

    The finally block will always be called (well not really always ... ) even if an exception is thrown or a return statement is reached (although that may be language dependent). It's a way to clean up that you know will always be called.

    0 讨论(0)
  • 2020-12-30 21:06

    @iAn and @mats:

    I would not "tear down" anything in finally {} that was "set up" within the try {} as a rule. Would be better to pull the stream creation outside of the try {}. If you need to handle an exception on stream create this could be done in a greater scope.

    StreamReader stream = new StreamReader("foo.bar");  
    try {
        mySendSomethingToStream(stream);
    }
    catch(noSomethingToSendException e) {
        //Swallow this    
        logger.error(e.getMessage());
    }
    catch(anotherTypeOfException e) {
        //More serious, throw this one back
        throw(e);
    }
    finally {
        stream.close();  
    }
    
    0 讨论(0)
  • 2020-12-30 21:07

    Well, for one thing, if you RETURN inside your try block, the finally will still run, but code listed below the try-catch-finally block will not.

    0 讨论(0)
  • 2020-12-30 21:08

    So you can clean up any open connections, etc. initialized in the try block. If you opened a connection and then an exception occurred, that exception would not be properly closed. This type of scenario is what the finally block is for.

    0 讨论(0)
  • @Ed, you might be thinking of something like a catch(...) that catches a non-specified exception in C++.

    But finally is code that will get executed no matter what happens in the catch blocks.

    Microsoft has a help page on try-finally for C#

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题