[英]How to suppress irrelevant errors in a try block
Suppose I want to check that a certain entry is in a Series.假设我想检查某个条目是否在系列中。 I would like to try to access that entry, and if that fails, raise a simple, short ValueError.我想尝试访问该条目,如果失败,则引发一个简单、简短的 ValueError。
For example, I have a series that doesn't have entry C
- I want a check to halt the script.例如,我有一个没有条目C
的系列 - 我想要检查以停止脚本。 Example:例子:
s = {'A': 1, 'B': 2}
s = pd.Series(s)
try:
s['C']
except:
raise ValueError('C is missing.')
But this code throws a long KeyError before spitting out the ValueError.但是这段代码在吐出 ValueError 之前抛出了一个很长的 KeyError。 It works, but is verbose.它有效,但很冗长。
(I know that I can use an assert statement instaead.) (我知道我可以使用 assert 语句 instaead。)
Why doesn't the try block suppress the KeyError - isn't that part of its purpose?为什么 try 块不抑制 KeyError - 这不是它的目的的一部分吗? Is there a way to get my intended behavior?有没有办法让我的预期行为?
You are seeing exception chaining .您正在看到异常链接。 This extra information can be suppressed with a from None
clause in your raise
statement.可以在raise
语句中使用from None
子句来抑制这些额外信息。 Consider this (totally contrived) case where I am suppressing a ZeroDivisionError
and raising a KeyError
:考虑这种(完全人为的)情况,我正在抑制ZeroDivisionError
并引发KeyError
:
>>> try:
... 1/0
... except ZeroDivisionError:
... raise KeyError
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
KeyError
But if I use from none
:但是如果我from none
使用:
>>> try:
... 1/0
... except ZeroDivisionError:
... raise KeyError from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
KeyError
>>>
Also note, you really should not use a bare except
clause .另请注意,您真的不应该使用裸except
子句。 Catch as specific an error as possible.捕获尽可能具体的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.