Golge Adam Golge Adam - 3 months ago 22
Python Question

try except block in function

I get

KeyError
when running following code:

r={'foo':'bar'} #no timestamp
def function(f=None):
try:
print(f) # giving r['timestamp'] KeyError
except:
print("problem")
function(f=r['timestamp'])


But this is working, it prints
problem
:

try:
print(r['timestamp']) # giving r['timestamp'] KeyError
except:
print("problem")


I can't understand why try-except block is not working in function.

Answer

function arguments are expressions that are evaluated before the value is passed to the function

so r['timestamp'] executes before function(f=...) an so before any try block captures any exceptions

you can use dict.get to avoid the KeyError:

function(f=r.get('timestamp', None))

or if you really need to capture the KeyError in the function:

def function(f=None):
    f = f or {}
    try:
        print(f['timestamp'])
    except KeyError:
        print("problem")
function(f=r)