管理python中的错误 [英] manage errors in python

查看:129
本文介绍了管理python中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要管理python错误。例如,当我键入:

 >>> 1/0 

我回馈:

 追溯(最近的最后一次呼叫):
文件< pyshell#14>,第1行,< module>
1/0
ZeroDivisionError:除以零

但是我需要保存这个错误在变量中。
我使用try..except为此:

 >>>尝试:
f(0)
除了异常作为错误:
打印(错误)

并在输出中看到:

 除以零

对我来说还不够我需要错误的行号,如IDLE(或其他IDE)
(我使用python 3.3,不能使用python 2.7)

解决方案

使用 traceback 模块提取特定信息,如行号:

 >>>尝试:
... f(0)
...除了异常作为错误:
... import traceback
... traceback.print_last()
...
追溯(最近的最后一次呼叫):
文件< stdin>,第1行,< module>
TypeError:不能将类型'float'的非int类型乘以序列


I need to manage python errors. For example when I type:

>>> 1/0

I give back:

Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    1/0
ZeroDivisionError: division by zero

but I need to save this error in a variable. I use try..except for this:

>>> try:
    f(0)
except Exception as err:
    print(err)

and see in output:

division by zero

It's not enough for me. I need to error lines numbers like to IDLE (or other IDE) (I use python 3.3 and can't use python 2.7)

解决方案

Use the traceback module to extract specific information such as line numbers:

>>> try:
...     f(0)
... except Exception as err:
...     import traceback
...     traceback.print_last()
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'

这篇关于管理python中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆