![](/img/trans.png)
[英]How can I handle multiple same Error type in Python in try except block
[英]How can I catch an error without using try/except?
有什么我可以用来捕获python中的错误而无需使用try / except吗?
我在想这样的事情:
main.py
from catch_errors import catch_NameError
print(this_variable_is_not_defined)
catch_errors.py
def catch_NameError(error):
if type(error) == NameError:
print("You didn't define the error")
输出为:
You didn't define the error
代替:
Traceback (most recent call last):
File "main.py", line 1, in <module>
print(this_variable_is_not_defined)
NameError: name 'this_variable_is_not_defined' is not defined
可以通过创建上下文管理器来完成,但是与显式try:except:
,它提供了可疑的好处。 您将必须使用with
语句,因此很清楚行为将在何处更改。 在此示例中,我使用contextlib.contextmanager
进行此操作,这节省了使用__enter__
和__exit__
方法创建类的__enter__
__exit__
。
from contextlib import contextmanager
@contextmanager
def IgnoreNameErrorExceptions():
"""Context manager to ignore NameErrors."""
try:
yield
except NameError as e:
print(e) # You can print whatever you want here.
with IgnoreNameErrorExceptions():
print(this_variable_is_not_defined)
这将输出
name 'this_variable_is_not_defined' is not defined
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.