[英]How to raise Exception with array?
I tried to throw an exception with array data:我试图用数组数据抛出异常:
raise Exception([ValidateError.YEAR, row])
When I tried to catch it I get this error:当我试图捕捉它时,我得到了这个错误:
'Exception' object is not subscriptable
Code is:代码是:
except Exception as e:
#invalid
print(e[0])
To access the Exception arguments you passed as a list, you should use .args
.要访问您作为列表传递的异常 arguments,您应该使用.args
。
So, I believe you were looking for the following:所以,我相信您正在寻找以下内容:
except Exception as e:
#valid
print(e.args[0][0])
As a side note, you can pass multiple arguments without them being in a list:作为旁注,您可以传递多个 arguments 而它们不在列表中:
raise Exception(ValidateError.YEAR, row)
And then you need one index less:然后你需要少一个索引:
except Exception as e:
#also valid
print(e.args[0])
You can subclass Exception
and implement the __getitem__
function like so:您可以子类化Exception
并像这样实现__getitem__
function :
class MyException(Exception):
def __init__(self, l):
self.l = l
def __getitem__(self, key):
return self.l[key]
try:
raise MyException([1, 2, 3])
except MyException as e:
print(e[0])
running it:运行它:
python3 main.py
1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.