Variables have a lifetime (scope) of the block they are declared in.
This will throw an exception because x is not defined.
try:
print(x)
except:
print("An exception occurred")
This one will work
try:
x = 5
print(x)
except:
print("An exception occurred")
What you need to do is declare your variable outside of the try scope.
Before the try scope so it the variable still exists in your except block.
x = 5
try:
print(x)
raise Exception("fail!")
except NameError:
print("Variable x is not defined")
except:
print(x)
print("Something else went wrong")
This will raise the exception but x will still have scope (lifetime) and will print out in the 2nd exception case.