63 8.8. Predefined Clean-up Actions Python Tutorial, Release 3.9.5 • If a$_{finally}$clause includes a$_{return}$statement, the returned value will be the one from the$_{finally}$ clause’s return statement, not the value from the try clause’s return statement. For example: A more complicated example: As you can see, the$_{finally}$clause is executed in any event. The$_{TypeError}$ raised by dividing two strings is not handled by the$_{except}$clause and therefore re-raised after the$_{finally}$ clause has been executed. In real world applications, the$_{finally}$clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful. Some objects define standard clean-up actions to be undertaken when the object is no longer needed, regardless of whether or not the operation using the object succeeded or failed. Look at the following example, which tries to open a file and print its contents to the screen. The problem with this code is that it leaves the file open for an indeterminate amount of time after this part of the code has finished executing. This is not an issue in simple scripts, but can be a problem for larger applications. The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly. for line in open("myfile.txt "): print(line, end ="") 8.8 Predefined Clean-up Actions >>> def divide(x, y): ... try : ... result=x /y ... except ZeroDivisionError : ... print("division by zero!") ... else : ... print("result is", result) ... finally : ... print("executing finally clause ") ... >>> divide(2,1) result is 2.0 executing finally clause >>> divide(2,0) division by zero! executing finally clause >>> divide("2","1") executing finally clause Traceback (most recent call last): File "<stdin>" , line1, in <module> File "<stdin>" , line3, in divide TypeError: unsupported operand type(s) for /: 'str' and 'str' >>> def bool_return (): ... try : ... return True ... finally : ... return False ... >>> bool_return() False