在Python中捕获一般异常是否合理,然后使用isinstance()
检测特定类型的异常以便正确处理它?</ p>
我现在正在使用dnspython工具包,它有一系列例外,例如超时,NXDOMAIN响应等。这些例外是dns.exception.DNSException
的子类,所以我想知道是否捕获DNSException
然后用isinstance()
检查特定异常是合理的还是pythonic。
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"
我是Python的新手,所以要温柔!
答案 0 :(得分:20)
这就是多个except
条款的用途:
try:
answers = dns.resolver.query(args.host)
except dns.resolver.NXDOMAIN:
print "No such domain %s" % args.host
except dns.resolver.Timeout:
print "Timed out while resolving %s" % args.host
except dns.exception.DNSException:
print "Unhandled exception"
注意子句的顺序:将采用第一个匹配子句,因此将超类的检查移到最后。
答案 1 :(得分:1)
从dns.resolver可以导入一些例外。 (未经测试的代码)
from dns.resolver import Resolver, NXDOMAIN, NoNameservers, Timeout, NoAnswer
try
host_record = self.resolver.query(self.host, "A")
if len(host_record) > 0:
Mylist['ERROR'] = False
# Do something
except NXDOMAIN:
Mylist['ERROR'] = True
Mylist['ERRORTYPE'] = NXDOMAIN
except NoNameservers:
Mylist['ERROR'] = True
Mylist['ERRORTYPE'] = NoNameservers
except Timeout:
Mylist['ERROR'] = True
Mylist['ERRORTYPE'] = Timeout
except NameError:
Mylist['ERROR'] = True
Mylist['ERRORTYPE'] = NameError