Some_function()在执行时引发异常,因此程序跳转到异常:
try:
some_function()
except:
print("exception happened!")
如何查看导致异常发生的原因?
Some_function()在执行时引发异常,因此程序跳转到异常:
try:
some_function()
except:
print("exception happened!")
如何查看导致异常发生的原因?
当前回答
希望这对你有帮助
import sys
varExcepHandling, varExcepHandlingZer = 2, 0
try:
print(varExcepHandling/varExcepHandlingZer)
except Exception as ex:
print(sys.exc_info())
'sys.exc_info()'将返回一个元组,如果你只想要异常类名,请使用'sys.exc_info()[0]'
注意:-如果你想看到所有的异常类,只需写入dir(__builtin__)
其他回答
除非某个函数是一个编码非常糟糕的遗留函数,否则你不应该需要你所要求的。
使用多个except子句以不同的方式处理不同的异常:
try:
someFunction()
except ValueError:
# do something
except ZeroDivision:
# do something else
重点是不应该捕获通用异常,而应该只捕获需要捕获的异常。我相信您不希望看到意外的错误或bug。
你的问题是:“我如何才能确切地看到someFunction()中发生了什么导致异常发生?”
在我看来,您不是在问如何处理生产代码中不可预见的异常(正如许多答案所假设的那样),而是在问如何找出在开发过程中导致特定异常的原因。
最简单的方法是使用调试器,该调试器可以在未捕获异常发生的地方停止,最好不要退出,以便您可以检查变量。例如,Eclipse开源IDE中的PyDev可以做到这一点。要在Eclipse中启用该功能,请打开Debug透视图,在Run菜单中选择管理Python异常断点,并在未捕获的异常上检查挂起。
你通常不应该用try来捕获所有可能的异常:…除非这太宽泛了。只要抓住那些无论出于什么原因都会发生的事情。如果您真的必须这样做,例如,如果您想在调试时了解有关某个问题的更多信息,那么您应该这样做
try:
...
except Exception as ex:
print ex # do whatever you want for debugging.
raise # re-raise exception.
使用下面的异常类型和异常文本
import sys
print(str(sys.exc_info()[0]).split(' ')[1].strip('>').strip("'")+"-"+(str(sys.exc_info()[1])))
如果你只想要异常类型:使用——>
import sys
print(str(sys.exc_info()[0]).split(' ')[1].strip('>').strip("'"))
由于Rajeshwar
大多数答案指向except(…)as(…):语法(正确),但同时没有人想谈论房间里的大象,而大象是sys.exc_info()函数。 来自sys模块的文档(重点是我的):
This function returns a tuple of three values that give information about the exception that is currently being handled. (…) If no exception is being handled anywhere on the stack, a tuple containing three None values is returned. Otherwise, the values returned are (type, value, traceback). Their meaning is: type gets the type of the exception being handled (a subclass of BaseException); value gets the exception instance (an instance of the exception type); traceback gets a traceback object (see the Reference Manual) which encapsulates the call stack at the point where the exception originally occurred.
我认为sys.exc_info()可以被视为对原始问题“我如何知道发生了什么类型的异常?”的最直接答案。