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

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

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


当前回答

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

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

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

其他回答

在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))

你可以像Lauritz推荐的那样开始:

except Exception as ex:

然后像这样打印ex:

try:
    #your try code here
except Exception as ex:
    print ex

大多数答案指向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()可以被视为对原始问题“我如何知道发生了什么类型的异常?”的最直接答案。

除非某个函数是一个编码非常糟糕的遗留函数,否则你不应该需要你所要求的。

使用多个except子句以不同的方式处理不同的异常:

try:
    someFunction()
except ValueError:
    # do something
except ZeroDivision:
    # do something else

重点是不应该捕获通用异常,而应该只捕获需要捕获的异常。我相信您不希望看到意外的错误或bug。

只要避免捕获异常,Python打印的回溯就会告诉你发生了什么异常。