python try:except:finally

后端 未结 8 2125
后悔当初
后悔当初 2020-12-23 17:36
# Open new file to write
file = None
try:
    file = open(filePath, \'w\')
except IOError:
    msg = (\"Unable to create file on disk.\")
    file.close()
    return         


        
8条回答
  •  粉色の甜心
    2020-12-23 17:47

    finally always gets called in the "end", even if an exception ocurrs. You can use this to make sure open resources are closed (for instance, a DB connection, a file, etc).

    I think you misunderstood the semantics.

    Your logic should be in the "try", you should deal with exceptions in the "except" block, and "finally" executes no matter how your method terminates, use it to clean up.

提交回复
热议问题