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)
可以在错误教程中找到更多信息.
我经常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)
| 归档时间: |
|
| 查看次数: |
3104 次 |
| 最近记录: |