Some_function()在执行时引发异常,因此程序跳转到异常:
try:
some_function()
except:
print("exception happened!")
如何查看导致异常发生的原因?
Some_function()在执行时引发异常,因此程序跳转到异常:
try:
some_function()
except:
print("exception happened!")
如何查看导致异常发生的原因?
当前回答
其他答案都指出不应该捕获通用异常,但似乎没有人愿意告诉您原因,这对于理解何时可以打破“规则”至关重要。下面是一个解释。基本上,这样你就不会隐藏:
发生错误的事实 发生错误的细节(错误隐藏反模式)
因此,只要您注意不做这些事情,就可以捕获泛型异常。例如,你可以用另一种方式向用户提供异常信息,比如:
在GUI中以对话框的形式显示异常 将异常从工作线程或进程转移到多线程或多处理应用程序中的控制线程或进程
那么如何捕捉泛型异常呢?有几种方法。如果你只想要一个异常对象,可以这样做:
try:
someFunction()
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
print message
Make sure message is brought to the attention of the user in a hard-to-miss way! Printing it, as shown above, may not be enough if the message is buried in lots of other messages. Failing to get the users attention is tantamount to swallowing all exceptions, and if there's one impression you should have come away with after reading the answers on this page, it's that this is not a good thing. Ending the except block with a raise statement will remedy the problem by transparently reraising the exception that was caught.
上述用法和使用just except: without any argument的区别有两个方面:
裸except:不提供要检查的异常对象 异常SystemExit, KeyboardInterrupt和GeneratorExit不会被上面的代码捕获,这通常是你想要的。参见异常层次结构。
如果你也想要与你没有捕获异常时得到的stacktrace相同,你可以像这样得到(仍然在except子句中):
import traceback
print traceback.format_exc()
如果你使用logging模块,你可以像这样将异常输出到日志中(以及一条消息):
import logging
log = logging.getLogger()
log.exception("Message for you, sir!")
如果你想更深入地研究堆栈,查看变量等,可以使用except块内pdb模块的post_mortem函数:
import pdb
pdb.post_mortem()
我发现最后一种方法在查找bug时非常有用。
其他回答
你可以像Lauritz推荐的那样开始:
except Exception as ex:
然后像这样打印ex:
try:
#your try code here
except Exception as ex:
print ex
在Python 2中,以下代码很有用
except Exception, exc:
# This is how you get the type
excType = exc.__class__.__name__
# Here we are printing out information about the Exception
print 'exception type', excType
print 'exception msg', str(exc)
# It's easy to reraise an exception with more information added to it
msg = 'there was a problem with someFunction'
raise Exception(msg + 'because of %s: %s' % (excType, exc))
大多数答案指向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()可以被视为对原始问题“我如何知道发生了什么类型的异常?”的最直接答案。
其他答案都指出不应该捕获通用异常,但似乎没有人愿意告诉您原因,这对于理解何时可以打破“规则”至关重要。下面是一个解释。基本上,这样你就不会隐藏:
发生错误的事实 发生错误的细节(错误隐藏反模式)
因此,只要您注意不做这些事情,就可以捕获泛型异常。例如,你可以用另一种方式向用户提供异常信息,比如:
在GUI中以对话框的形式显示异常 将异常从工作线程或进程转移到多线程或多处理应用程序中的控制线程或进程
那么如何捕捉泛型异常呢?有几种方法。如果你只想要一个异常对象,可以这样做:
try:
someFunction()
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
print message
Make sure message is brought to the attention of the user in a hard-to-miss way! Printing it, as shown above, may not be enough if the message is buried in lots of other messages. Failing to get the users attention is tantamount to swallowing all exceptions, and if there's one impression you should have come away with after reading the answers on this page, it's that this is not a good thing. Ending the except block with a raise statement will remedy the problem by transparently reraising the exception that was caught.
上述用法和使用just except: without any argument的区别有两个方面:
裸except:不提供要检查的异常对象 异常SystemExit, KeyboardInterrupt和GeneratorExit不会被上面的代码捕获,这通常是你想要的。参见异常层次结构。
如果你也想要与你没有捕获异常时得到的stacktrace相同,你可以像这样得到(仍然在except子句中):
import traceback
print traceback.format_exc()
如果你使用logging模块,你可以像这样将异常输出到日志中(以及一条消息):
import logging
log = logging.getLogger()
log.exception("Message for you, sir!")
如果你想更深入地研究堆栈,查看变量等,可以使用except块内pdb模块的post_mortem函数:
import pdb
pdb.post_mortem()
我发现最后一种方法在查找bug时非常有用。
你的问题是:“我如何才能确切地看到someFunction()中发生了什么导致异常发生?”
在我看来,您不是在问如何处理生产代码中不可预见的异常(正如许多答案所假设的那样),而是在问如何找出在开发过程中导致特定异常的原因。
最简单的方法是使用调试器,该调试器可以在未捕获异常发生的地方停止,最好不要退出,以便您可以检查变量。例如,Eclipse开源IDE中的PyDev可以做到这一点。要在Eclipse中启用该功能,请打开Debug透视图,在Run菜单中选择管理Python异常断点,并在未捕获的异常上检查挂起。