在Python中捕獲一個泛型異常是否合理,然後使用isinstance()
來檢測特定類型的異常以便適當地處理它?在Python中使用isinstance檢查特定類型的異常是否合理?
我現在正在使用dnspython工具包,它有一些例外情況,例如超時,NXDOMAIN響應等。這些例外是dns.exception.DNSException
的子類,所以我想知道它是否合理,或pythonic,趕上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,所以要溫柔!
謝謝斯文......看起來好多了。 – Vortura 2012-02-12 00:03:28