user2856064 user2856064 - 29 days ago 11
Python Question

How to proper ommit UnboundLocalError: Local variable '' referenced before assignment when exception has been thrown?

Function a() and b() can throw an exception. This code does not handle while exception is throwing during the assignment "UnboundLocalError: Local variable 'x' referenced before assignment"
Code:

def foo():
try:
x = a('test')
b(x, 'test2')
except Exception as ex:
raise Exception('Message error: ' + str(x) + " " + str(ex)) #here could be UnboundLocalError: Local variable 'x' referenced before assignment


My solution is:

def foo():
try:
x = a('test')
try:
b(x, 'test2')
except Exception as ex:
raise Exception('Message error: ' + str(x) + " " + str(ex))
except Exception as ex:
raise Exception('Message error: ' + str(ex))


Is it possible to do it more tricky, elegant? Now I`m forced to use double try except template.

Answer Source

This is probably one way you could do it:

try:
    x = a('test')
    b(x, 'test2')
except Exception as ex:
    if not 'x' in locals():
        x = 'undefined'
    raise Exception('Message error: ' + str(x) + " " + str(ex))

Personally, I think catching both exceptions in separate try/except blocks is more elegant, as it shows the reader that a() did not successfully complete and disallows an UnboundLocalError which masks the real issue:

try:
    x = a('test')
except Exception as ex:
   raise Exception('oh no, a() failed')
try:
    b(x, 'test2')
except Exception as ex:
    raise Exception('oops, b() failed')

Here is some documentation about locals(): https://docs.python.org/3/library/functions.html#locals