python try:except:finally

后端 未结 8 2123
后悔当初
后悔当初 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:55

    If the file is not opened, the line file = open(filePath, 'w') fails, so nothing gets assigned to file.

    Then, the except clause runs, but nothing is in file, so file.close() fails.

    The finally clause always runs, even if there was an exception. And since file is still None you get another exception.

    You want an else clause instead of finally for things that only happen if there was no exception.

        try:
            file = open(filePath, 'w')
        except IOError:
            msg = "Unable to create file on disk."
            return
        else:
            file.write("Hello World!")
            file.close()
    

    Why the else? The Python docs say:

    The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.

    In other words, this won't catch an IOError from the write or close calls. Which is good, because then reason woudn't have been “Unable to create file on disk.” – it would have been a different error, one that your code wasn't prepared for. It's a good idea not to try to handle such errors.

提交回复
热议问题