Search code examples
pythonexceptfinally

Python: Does finally needs a try-except clause?


Suppose the following code.

try:
    some_code_1
except: # will it be called twice, if an error occures in finally?
    some_code_2
finally:
    some_code_3

Suppose an exception occurs in some_code_3. Do I need an extra try-except clause around some_code_3 (see below) or will the exception with some_code_2 be called again, which in principle could cause an infinite loop?

Is this saver?

try:
    some_code_1
except: # will it be called twice, if an error occures in finally?
    some_code_2
finally:
    try:
        some_code_3
    except:
        pass

Solution

  • Just give it a try:

    try:
        print(abc) #Will raise NameError
    except: 
        print("In exception")
    finally:
        print(xyz) #Will raise NameError
    
    Output: 
    In exception
    Traceback (most recent call last):
      File "Z:/test/test.py", line 7, in <module>
        print(xyz)
    NameError: name 'xyz' is not defined
    

    So no, it doesn't end up in an infinite loop