Some_function()在执行时引发异常,因此程序跳转到异常:
try:
some_function()
except:
print("exception happened!")
如何查看导致异常发生的原因?
Some_function()在执行时引发异常,因此程序跳转到异常:
try:
some_function()
except:
print("exception happened!")
如何查看导致异常发生的原因?
当前回答
为了补充Lauritz的答案,我创建了一个用于异常处理的装饰器/包装器,并且包装器记录发生了哪种类型的异常。
class general_function_handler(object):
def __init__(self, func):
self.func = func
def __get__(self, obj, type=None):
return self.__class__(self.func.__get__(obj, type))
def __call__(self, *args, **kwargs):
try:
retval = self.func(*args, **kwargs)
except Exception, e :
logging.warning('Exception in %s' % self.func)
template = "An exception of type {0} occured. Arguments:\n{1!r}"
message = template.format(type(e).__name__, e.args)
logging.exception(message)
sys.exit(1) # exit on all exceptions for now
return retval
这可以在类方法或带有装饰器的独立函数上调用:
@general_function_handler
完整的例子请参阅我的博客:http://ryaneirwin.wordpress.com/2014/05/31/python-decorators-and-exception-handling/
其他回答
你通常不应该用try来捕获所有可能的异常:…除非这太宽泛了。只要抓住那些无论出于什么原因都会发生的事情。如果您真的必须这样做,例如,如果您想在调试时了解有关某个问题的更多信息,那么您应该这样做
try:
...
except Exception as ex:
print ex # do whatever you want for debugging.
raise # re-raise exception.
大多数答案指向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()可以被视为对原始问题“我如何知道发生了什么类型的异常?”的最直接答案。
使用类型class和as语句
try:#code
except Exception as e:
m=type(e)
#m is the class of the exception
strm=str(m)
#strm is the string of m
实际的异常可以通过以下方式捕获:
try:
i = 1/0
except Exception as e:
print e
您可以从Python教程中了解有关异常的更多信息。
只要避免捕获异常,Python打印的回溯就会告诉你发生了什么异常。