Some_function()在执行时引发异常,因此程序跳转到异常:

try:
    some_function()
except:
    print("exception happened!")

如何查看导致异常发生的原因?


当前回答

这些答案很适合调试,但对于以编程方式测试异常,isinstance(e, SomeException)可能很方便,因为它也测试SomeException的子类,因此您可以创建应用于异常层次结构的功能。

其他回答

你通常不应该用try来捕获所有可能的异常:…除非这太宽泛了。只要抓住那些无论出于什么原因都会发生的事情。如果您真的必须这样做,例如,如果您想在调试时了解有关某个问题的更多信息,那么您应该这样做

try:
    ...
except Exception as ex:
    print ex # do whatever you want for debugging.
    raise    # re-raise exception.

这些答案很适合调试,但对于以编程方式测试异常,isinstance(e, SomeException)可能很方便,因为它也测试SomeException的子类,因此您可以创建应用于异常层次结构的功能。

实际的异常可以通过以下方式捕获:

try:
    i = 1/0
except Exception as e:
    print e

您可以从Python教程中了解有关异常的更多信息。

你可以像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))