在Python中,捕获通用异常后使用isinstance()
检测特定类型的异常以便适当处理它,这样做是否合理?
目前我正在使用dnspython工具包进行测试,它有各种异常,如超时、NXDOMAIN响应等。 这些异常都是dns.exception.DNSException
的子类,所以我想知道是否合理或符合Python惯例,来捕获DNSException
然后使用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的新手,请温柔一点!