finally

Does 'finally' always execute in Python?

Does 'finally' always execute in Python? Question: For any possible try-finally block in Python, is it guaranteed that the finally block will always be executed? For example, let’s say I return while in an except block: try: 1/0 except ZeroDivisionError: return finally: print(“Does this code run?”) Or maybe I re-raise an Exception: try: 1/0 except …

Total answers: 6

'Finally' equivalent for If/Elif statements in Python

'Finally' equivalent for If/Elif statements in Python Question: Does Python have a finally equivalent for its if/else statements, similar to its try/except/finally statements? Something that would allow us to simplify this: if condition1: do stuff clean up elif condition2: do stuff clean up elif condition3: do stuff clean up … … to this: if condition1: …

Total answers: 9

Why is `continue` not allowed in a `finally` clause in Python?

Why is `continue` not allowed in a `finally` clause in Python? Question: The following code raises a syntax error: >>> for i in range(10): … print i … try: … pass … finally: … continue … print i … File “<stdin>”, line 6 SyntaxError: ‘continue’ not supported inside ‘finally’ clause Why isn’t a continue statement …

Total answers: 7

Using python "with" statement with try-except block

Using python "with" statement with try-except block Question: Is this the right way to use the python “with” statement in combination with a try-except block?: try: with open(“file”, “r”) as f: line = f.readline() except IOError: <whatever> If it is, then considering the old way of doing things: try: f = open(“file”, “r”) line = …

Total answers: 4

return eats exception

return eats exception Question: I found the following behavior at least weird: def errors(): try: ErrorErrorError finally: return 10 print errors() # prints: 10 # It should raise: NameError: name ‘ErrorErrorError’ is not defined The exception disappears when you use return inside a finally clause. Is that a bug? Is that documented anywhere? But the …

Total answers: 4