我的脚本中有一个 try
/finally
子句。在 finally
子句中是否可能获取确切的错误消息?
我的脚本中有一个 try
/finally
子句。在 finally
子句中是否可能获取确切的错误消息?
finally
块中sys.exc_info
始终为全None。请使用以下方法:try:
whatever
except:
here sys.exc_info is valid
to re-raise the exception, use a bare `raise`
else:
here you know there was no exception
finally:
and here you can do exception-independent finalization
finally
块将会被执行,无论是否抛出异常。正如Josh所指出的那样,你很可能不想在那里处理它。except
块中捕获异常,并适当地处理或重新引发它,然后在finally块中使用该值--并期望在执行过程中没有抛出异常时可能从未被设置。import sys
exception_name = exception_value = None
try:
# do stuff
except Exception as e:
exception_name, exception_value, _ = sys.exc_info()
raise # or don't -- it's up to you
finally:
# do something with exception_name and exception_value
# but remember that they might still be none
实际上,其他答案有点模糊。让我澄清一下。你可以在finally块中随时调用sys.exc_info()。但是,它的输出将取决于异常是否实际上已被引发。
import sys
def f(i):
try:
if i == 1:
raise Exception
except Exception as e:
print "except -> " + str(sys.exc_info())
finally:
print "finally -> " + str(sys.exc_info())
f(0)
f(1)
>>>
finally -> (None, None, None)
except -> (<type 'exceptions.Exception'>, Exception(), <traceback object at 0x029438F0>)
finally -> (<type 'exceptions.Exception'>, Exception(), <traceback object at 0x029438F0>)
import sys
def f(i):
try:
if i == 1:
raise Exception
except Exception as e:
print "except -> " + str(sys.exc_info())
finally:
print "finally -> " + str(sys.exc_info())
def f1(i):
if i == 0:
try:
raise Exception('abc')
except Exception as e:
pass
f(i)
f1(0)
f1(1)
>>>
finally -> (<type 'exceptions.Exception'>, Exception('abc',), <traceback object at 0x02A33940>)
except -> (<type 'exceptions.Exception'>, Exception(), <traceback object at 0x02A33990>)
finally -> (<type 'exceptions.Exception'>, Exception(), <traceback object at 0x02A33990>)
我希望这能使事情更加清晰明了。
f(1)
的输出是finally -> (None, None, None)
,因此你不能轻易地在finally块中获取异常。 - coldfixfinally
时刻sys.exc_info
都是全部为None。请使用[这个]代替:…except
子句中处理这个问题。import sys
try:
int("not an integer LOL")
except:
e = sys.exc_info()[1]
# isinstance(e, ValueError) == True
raise # this line is optional; I have it commented for the example output
else:
e = None # you should do this to avoid a NameError
finally:
print("I really wanted to access %s inside of a finally clause. And I'm doing so now."
% repr(e))
我真的想在 finally 子句中访问
ValueError("invalid literal for int() with base 10: 'not an integer LOL'")
。现在我正在这样做。
你应该在 except 子句中执行此操作,而不是 finally 中。
参考:http://www.doughellmann.com/articles/Python-Exception-Handling/
finally:
块中访问sys.exc_info
。 - Kentzosys.exc_info()
返回(None, None, None)
。 - Jonathan