[英]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.