在 Python 中捕获通用异常是否合理,然后用于isinstance()
检测特定类型的异常以便适当地处理它?
我目前正在使用 dnspython 工具包,它有一系列异常,例如超时、NXDOMAIN 响应等。这些异常是 的子类dns.exception.DNSException
,所以我想知道捕获它是否合理或 pythonicDNSException
然后使用 . 检查特定异常isinstance()
。
例如
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 新手,所以要温柔!