Tryblock location
Why is the tryblock after the definition of the function?
1 answers ( 0 marked as helpful)
Hey Sara,
Thank you for reaching out!
In the code snippet below, I've defined a function that contains a single letter. The code in the body should raise an error, as the variable a
is not defined inside the function. Notice, however, that the first cell, containing the definition of bad_function()
, executes without any errors. It is only when we call the function in the next cell that the body of the function is executed, thereby throwing a NameError
.
That is to say, surrounding function definitions with try-except
blocks is unnecessary. It only makes sense to use a try-except
block when calling an already defined function.
Hope this helps!
Kind regards,
365 Hristina