如何在python中显示为什么"尝试"失败

cal*_*pto 9 python error-handling

无论如何要显示"尝试"失败的原因,并跳过"除外",而不用手写出所有可能的错误,并且没有结束程序?

例:

try:
    1/0
except:
    someway to show 
    "Traceback (most recent call last):
       File "<pyshell#0>", line 1, in <module>
         1/0
    ZeroDivisionError: integer division or modulo by zero"
Run Code Online (Sandbox Code Playgroud)

我不想这样做if:print error 1, elif: print error 2, elif: etc....我想看到显示的错误try没有出现

mik*_*iku 10

尝试:

>>> try:
...     1/0
... except Exception, e:
...    print e
... 
integer division or modulo by zero
Run Code Online (Sandbox Code Playgroud)

还有其他语法变体,例如:

>>> try:
...     1/0
... except Exception as e:
...    print e
... 
integer division or modulo by zero
Run Code Online (Sandbox Code Playgroud)

可以在错误教程中找到更多信息.


Mic*_*las 8

我经常traceback用来记录这样的异常来记录或显示在stderr上:

import traceback
import sys

try:
    print 1/0
except Exception:
    s = traceback.format_exc()
    serr = "there were errors:\n%s\n" % (s)
    sys.stderr.write(serr) 
Run Code Online (Sandbox Code Playgroud)

输出将显示有关行发生异常的行的信息:

there were errors:
Traceback (most recent call last):
  File "c:\test\ex.py", line 5, in <module>
    print 1/0
ZeroDivisionError: integer division or modulo by zero
Run Code Online (Sandbox Code Playgroud)

  • 来自http://www.python.org/dev/peps/pep-0008/:"在捕获异常时,尽可能提及特定的异常,而不是使用裸的'except:'子句.[...] A bare'除外:'子句将捕获SystemExit和KeyboardInterrupt异常,使得使用Control-C中断程序变得更加困难,并且可以掩盖其他问题.如果要捕获发出程序错误信号的所有异常,请使用'除异常:'." (2认同)