函数a()和b()会抛出异常。如何正确地省略UnboundLocalError:在抛出异常时赋值之前引用的局部变量“'?
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
我的解决办法是: 代码:“赋值之前引用局部变量‘X’UnboundLocalError”,而例外的是分配期间抛出这个代码不处理
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))
是否有可能做它更棘手,优雅?现在我不得不使用除模板外的双重尝试。
为什么你需要首先引用'x'异常消息? – roganjosh
此外,将第一个块中的两个函数捆绑到一个全部例外中并不是一个好主意(或者一般情况下使用一个“except”)。 'x = a('test')'失败还是'b(x,'test2')'?目前,你解密的方式是提出另一个未被捕获的异常。 – roganjosh