在 Python 中使用 isinstance 检查特定类型的异常是否合理?
在Python中捕获通用异常,然后使用isinstance()来检测特定类型的异常以便适当地处理它是否合理?
我现在正在使用 dnspython 工具包,它有一系列异常,例如超时、NXDOMAIN 响应等。这些异常是 dns.exception.DNSException 的子类,因此我想知道捕获 DNSException
然后使用 isinstance()
检查特定异常是否合理或符合 Python 风格。
例如,
try:
answers = dns.resolver.query(args.host)
except dns.exception.DNSException as e:
if isinstance(e, dns.resolver.NXDOMAIN):
print "No such domain %s" % args.host
elif isinstance(e, dns.resolver.Timeout):
print "Timed out while resolving %s" % args.host
else:
print "Unhandled exception"
我是 Python 新手,所以要温柔!
Is it reasonable in Python to catch a generic exception, then use isinstance()
to detect the specific type of exception in order to handle it appropriately?
I'm playing around with the dnspython toolkit at the moment, which has a range of exceptions for things like a timeout, an NXDOMAIN response, etc. These exceptions are subclasses of dns.exception.DNSException
, so I am wondering if it's reasonable, or pythonic, to catch DNSException
then check for a specific exception with isinstance()
.
e.g.
try:
answers = dns.resolver.query(args.host)
except dns.exception.DNSException as e:
if isinstance(e, dns.resolver.NXDOMAIN):
print "No such domain %s" % args.host
elif isinstance(e, dns.resolver.Timeout):
print "Timed out while resolving %s" % args.host
else:
print "Unhandled exception"
I'm new to Python so be gentle!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是多个
except
子句的用途:请注意子句的顺序:将采用第一个匹配的子句,因此将对超类的检查移至末尾。
That's what multiple
except
clauses are for:Be careful about the order of the clauses: The first matching clause will be taken, so move the check for the superclass to the end.
您可以从 dns.resolver 导入一些异常。
(未经测试的代码)
From dns.resolver you can import some exceptions.
(untested code)