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

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

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


当前回答

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

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

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

其他回答

使用下面的异常类型和异常文本

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

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

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打印的回溯就会告诉你发生了什么异常。

获取异常对象所属类的名称:

e.__class__.__name__

使用print_exc()函数也将打印堆栈跟踪,这是任何错误消息的基本信息。

是这样的:

from traceback import print_exc

class CustomException(Exception): pass

try:
    raise CustomException("hi")
except Exception as e:
    print ('type is:', e.__class__.__name__)
    print_exc()
    # print("exception happened!")

你会得到这样的输出:

type is: CustomException
Traceback (most recent call last):
  File "exc.py", line 7, in <module>
    raise CustomException("hi")
CustomException: hi

在打印和分析之后,代码可以决定不处理异常,只执行raise:

from traceback import print_exc

class CustomException(Exception): pass

def calculate():
    raise CustomException("hi")

try:
    calculate()
except CustomException as e:
    # here do some extra steps in case of CustomException
    print('custom logic doing cleanup and more')
    # then re raise same exception
    raise

输出:

custom logic doing cleanup and more

和解释器打印异常:

Traceback (most recent call last):
  File "test.py", line 9, in <module>
    calculate()
  File "test.py", line 6, in calculate
    raise CustomException("hi")
__main__.CustomException: hi

引发后,原始异常继续向上传播调用堆栈。(注意可能的陷阱)如果你引发新的异常,它会携带新的(更短的)堆栈跟踪。

from traceback import print_exc

class CustomException(Exception):
    def __init__(self, ok):
        self.ok = ok

def calculate():
    raise CustomException(False)

try:
    calculate()
except CustomException as e:
    if not e.ok:
        # Always use `raise` to rethrow exception
        # following is usually mistake, but here we want to stress this point
        raise CustomException(e.ok)
    print("handling exception")

输出:

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    raise CustomException(e.message)
__main__.CustomException: hi    

注意traceback如何不包括第9行中的compute()函数,这是原始异常e的起源。