简体   繁体   English

引发Python内置异常时如何设置它的message属性

[英]How do I set a Python builtin Exception's message attribute when I raise it

I know I can specify an arbitrary number of arguments to an Exception (or any subclass thereof) when I raise it, but I see that Exceptions have a message attribute which isn't populated. 我知道在引发异常时可以为Exception(或其任何子类)指定任意数量的参数,但是我看到Exception具有未填充的message属性。

def throw():
    raise Exception("This is my message", 10)

try:
    throw()
except Exception as E:
    print "message = ", E.message
    print E.args

produces 产生

message = 
("This is my message", 10)

What I would like to do is raise a variety ValueErrors depending on how or why a value in my function isn't valid. 我想做的是根据我的函数中的值无效或无效的方式引发各种ValueErrors。 I would also like to attach a code, so something like 我还想附加一个代码,例如

raise ValueError(1, "You need to supply a string value")
# or
raise ValueError(2, "Not a valid place name") #but it is a valid string

I'm writing a code that runs callbacks supplied by the user, and I expect the user's functions to raise ValueErrors in certain situations, but their callback can also call into some library functions I provide, and I want to be able distinguish between the user's ValueErrors and Mine. 我正在编写运行用户提供的回调的代码,我希望用户的函数在某些情况下会引发ValueErrors,但它们的回调也可以调用我提供的某些库函数,并且我希望能够区分用户的ValueErrors和我的。

I know I can subclass the ValueError and check for that exception type explicitly, but that seems like overkill. 我知道我可以继承ValueError的子类,并显式检查该异常类型,但这似乎有点过头了。 These are all errors with user supplied values after all, so I would like to use the first argument to the exception as a code, and then somehow set the message attribute explicitly 毕竟,这些都是用户提供的值的错误,因此我想将异常的第一个参数用作代码,然后以某种方式显式设置message属性

raise ValueError(10, message = "Error 10 is something quite specific")

The above doesn't work, because exceptions don't accept keyword arguments on init . 上面的方法不起作用,因为异常不接受init上的关键字参数。

You can pass multiple argument when you raise an exception: 引发异常时可以传递多个参数:

try:
    raise ValueError("message", 1, 2, 3)
except ValueError as e:
    print e
    print e[1]

The exception object is simply a tuple, and you can access any item in te tuple in array[index] manner. 异常对象只是一个元组,您可以以array [index]的方式访问元组中的任何项目。

OUTPUT: OUTPUT:

('message', 1, 2, 3)
1

The message attribute is set when the Exception instance is created with a single argument. 当使用单个参数创建Exception实例时,将设置message属性。 Otherwise it is empty: 否则为空:

In [1]: Exception(42).message
Out[1]: 42

In [2]: Exception('foo').message
Out[2]: 'foo'

In [3]: Exception('foo', 42).message
Out[3]: ''

Of course you can create an instance of Exception and manually set its .message attribute before raising: 当然,您可以创建Exception的实例并在引发之前手动设置其.message属性:

e = Exception()
e.message = 'test'
raise e

But it would probably make a lot of sense to use a custom exception class instead. 但是,改用自定义异常类可能很有意义。

Also note that Exception does not have a message attribute in Python 3, only args . 另请注意,Python 3中Exception没有message属性,只有args

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Python 中使用自定义消息引发相同的异常? - How do I raise the same Exception with a custom message in Python? 如何使用 Try 和 Exception 在 Python 中引发带有打印消息的错误? - How do I use a Try and Exception to raise an error with a print message in Python? 分配给未映射到 SQLAlchemy 列的属性时如何引发异常? - How do I raise an exception when assigning to an attribute which is NOT mapped to an SQLAlchemy column? 如何在Python 2.7中引发自己的异常? - How do I raise my own Exception in Python 2.7? 当用户想在Python中使用import *导入所有内容时,如何引发异常? - How do I raise an exception when user wants to import everything using import * in Python? 将integer-as-string转换为int时,如何不引发Python异常 - How do I not raise a Python exception when converting an integer-as-string to an int 模拟 - 如何在调用者上引发异常? - Mocking - How do I raise exception on the caller? 在python 3.6中,如何捕获异常并引发异常以便以后处理? - In python 3.6, how do I catch an exception and raise an exception to be handled later? 在“尝试”中的“提高”,何时以及如何使用“提高”? - 'raise' inside 'try' , when and how do I use 'raise? 当请求非法状态时我应该提出什么Python异常? - What Python Exception should I raise when illegal state is asked for?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM