python如何定义i_如何在Python中使用自定义消息引发相同的Exception?

如何在Python中使用自定义消息引发相同的Exception?

我的代码中有这个ValueError块:

try:

do_something_that_might_raise_an_exception()

except ValueError as err:

errmsg = 'My custom error message.'

raise ValueError(errmsg)

严格来说,我实际上是在筹集另一个ValueError,而不是由ValueError引发的ValueError,在这种情况下称为err。 如何将自定义信息附加到err? 我尝试以下代码但由于err,一个ValueError实例失败,因此无法调用:

try:

do_something_that_might_raise_an_exception()

except ValueError as err:

errmsg = 'My custom error message.'

raise err(errmsg)

Kit asked 2019-07-25T23:42:40Z

10个解决方案

110 votes

我意识到这个问题已经存在了一段时间,但是一旦你足够幸运只支持python 3.x,这真的变得美丽了:)

来自

我们可以使用raise from来链接异常。

try:

1 / 0

except ZeroDivisionError as e:

raise Exception('Smelly socks') from e

在这种情况下,调用者将捕获的异常具有我们引发异常的地方的行号。

Traceback (most recent call last):

File "test.py", line 2, in

1 / 0

ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):

File "test.py", line 4, in

raise Exception('Smelly socks') from e

Exception: Smelly socks

注意底部异常只有我们引发异常的堆栈跟踪。 您的调用者仍然可以通过访问他们捕获的异常的__cause__属性来获取原始异常。

with_traceback

或者你可以使用with_traceback。

try:

1 / 0

except ZeroDivisionError as e:

raise Exception('Smelly socks').with_traceback(e.__traceback__)

使用此表单,调用者将捕获的异常具有发生原始错误的位置的回溯。

Traceback (most recent call last):

File "test.py", line 2, in

1 / 0

ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "test.py", line 4, in

raise Exception('Smelly socks').with_traceback(e.__traceback__)

File "test.py", line 2, in

1 / 0

Exception: Smelly socks

请注意,底部异常具有我们执行无效除法的行以及我们重新加载异常的行。

Ben answered 2019-07-25T23:44:56Z

71 votes

更新:对于Python 3,请查看Ben的答案

要将消息附加到当前异常并重新引发它:(外部尝试/除了只是为了显示效果)

对于python 2.x,其中x> = 6:

try:

try:

raise ValueError # something bad...

except ValueError as err:

err.message=err.message+" hello"

raise # re-raise current exception

except ValueError as e:

print(" got error of type "+ str(type(e))+" with message " +e.message)

如果ValueError是从ValueError派生的,这也将是正确的。例如.message。

请注意,您可以添加任何您喜欢的内容到.message.例如,ValueError。

编辑:@Ducan在评论中指出以上不适用于python 3,因为.message不是ValueError的成员。相反,你可以使用它(有效的python 2.6或更高版本或3.x):

try:

try:

raise ValueError

except ValueError as err:

if not err.args:

err.args=('',)

err.args = err.args + ("hello",)

raise

except ValueError as e:

print(" error was "+ str(type(e))+str(e.args))

EDIT2:

根据目的,您还可以选择在自己的变量名称下添加额外信息。 对于python2和python3:

try:

try:

raise ValueError

except ValueError as err:

err.extra_info = "hello"

raise

except ValueError as e:

print(" error was "+ str(type(e))+str(e))

if 'extra_info' in dir(e):

print e.extra_info

Johan Lundberg answered 2019-07-25T23:43:36Z

7 votes

try:

try:

int('a')

except ValueError as e:

raise ValueError('There is a problem: {0}'.format(e))

except ValueError as err:

print err

打印:

There is a problem: invalid literal for int() with base 10: 'a'

eumiro answered 2019-07-25T23:45:16Z

5 votes

似乎所有答案都是向e.args [0]添加信息,从而改变了现有的错误信息。 相反,扩展args元组是否有缺点? 我认为可能的好处是,您可以单独保留原始错误消息,以用于需要解析该字符串的情况; 如果您的自定义错误处理产生了多个消息或错误代码,并且可以通过编程方式解析回溯(例如通过系统监视工具),则可以向元组添加多个元素。

## Approach #1, if the exception may not be derived from Exception and well-behaved:

def to_int(x):

try:

return int(x)

except Exception as e:

e.args = (e.args if e.args else tuple()) + ('Custom message',)

raise

>>> to_int('12')

12

>>> to_int('12 monkeys')

Traceback (most recent call last):

File "", line 1, in

File "", line 3, in to_int

ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')

要么

## Approach #2, if the exception is always derived from Exception and well-behaved:

def to_int(x):

try:

return int(x)

except Exception as e:

e.args += ('Custom message',)

raise

>>> to_int('12')

12

>>> to_int('12 monkeys')

Traceback (most recent call last):

File "", line 1, in

File "", line 3, in to_int

ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')

你能看到这种方法的缺点吗?

Chris Johnson answered 2019-07-25T23:45:51Z

2 votes

此代码模板应允许您使用自定义消息引发异常。

try:

raise ValueError

except ValueError as err:

raise type(err)("my message")

Ruggero Turra answered 2019-07-25T23:46:17Z

2 votes

这是我用来修改Python 2.7和3.x中的异常消息同时保留原始回溯的函数。 它需要six

def reraise_modify(caught_exc, append_msg, prepend=False):

"""Append message to exception while preserving attributes.

Preserves exception class, and exception traceback.

Note:

This function needs to be called inside an except because

`sys.exc_info()` requires the exception context.

Args:

caught_exc(Exception): The caught exception object

append_msg(str): The message to append to the caught exception

prepend(bool): If True prepend the message to args instead of appending

Returns:

None

Side Effects:

Re-raises the exception with the preserved data / trace but

modified message

"""

ExceptClass = type(caught_exc)

# Keep old traceback

traceback = sys.exc_info()[2]

if not caught_exc.args:

# If no args, create our own tuple

arg_list = [append_msg]

else:

# Take the last arg

# If it is a string

# append your message.

# Otherwise append it to the

# arg list(Not as pretty)

arg_list = list(caught_exc.args[:-1])

last_arg = caught_exc.args[-1]

if isinstance(last_arg, str):

if prepend:

arg_list.append(append_msg + last_arg)

else:

arg_list.append(last_arg + append_msg)

else:

arg_list += [last_arg, append_msg]

caught_exc.args = tuple(arg_list)

six.reraise(ExceptClass,

caught_exc,

traceback)

Bryce Guinta answered 2019-07-25T23:46:43Z

1 votes

Python 3内置异常有strerror字段:

except ValueError as err:

err.strerror = "New error message"

raise err

user3761308 answered 2019-07-25T23:47:09Z

1 votes

使用您的错误消息引发新异常

raise Exception('your error message')

要么

raise ValueError('your error message')

在您想要引发它的地方或使用'from'将错误消息附加(替换)到当前异常中:

except ValueError as e:

raise ValueError('your message') from e

Alexey Antonenko answered 2019-07-25T23:47:44Z

0 votes

当前的答案对我来说效果不好,如果没有重新捕获异常,则不会显示附加的消息。

但是,无论是否重新捕获异常,执行下面的操作都会保留跟踪并显示附加的消息。

try:

raise ValueError("Original message")

except ValueError as err:

t, v, tb = sys.exc_info()

raise t, ValueError(err.message + " Appended Info"), tb

(我使用的是Python 2.7,还没有在Python 3中尝试过)

Zitrax answered 2019-07-25T23:48:25Z

-2 votes

如果要自定义错误类型,您可以做的一件简单事情是基于ValueError定义错误类。

igni answered 2019-07-25T23:48:51Z

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值