在Python中获取异常值 [英] Getting the exception value in Python

查看:139
本文介绍了在Python中获取异常值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有该代码:

try:
    some_method()
except Exception, e:

如何获取此异常值(我的意思是字符串
)?

How can I get this Exception value (string representation I mean)?

推荐答案

使用 str

try:
    some_method()
except Exception as e:
    s = str(e)

此外,大多数异常类都具有 args 属性。通常, args [0] 会是错误消息。

Also, most exception classes will have an args attribute. Often, args[0] will be an error message.

请注意,仅使用<$ c如果没有错误消息,$ c> str 将返回一个空字符串,而pyfunc建议使用 repr 至少会显示异常的类。我的看法是,如果要打印出来,它是针对最终用户的,他们不关心类是什么,只想输入错误消息。

It should be noted that just using str will return an empty string if there's no error message whereas using repr as pyfunc recommends will at least display the class of the exception. My take is that if you're printing it out, it's for an end user that doesn't care what the class is and just wants an error message.

它真的取决于您要处理的异常类及其实例化方式。您有什么特别的主意吗?

It really depends on the class of exception that you are dealing with and how it is instantiated. Did you have something in particular in mind?

这篇关于在Python中获取异常值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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