2012-02-11 78 views
8

在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,所以要溫柔!

回答

16

這就是多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" 

小心有關條款的順序:第一個匹配子句將採取,所以移動支票超到了最後。

+0

謝謝斯文......看起來好多了。 – Vortura 2012-02-12 00:03:28

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 
+0

+1與答案:如果已知例外情況,最好使用不同的「except」塊。但是最後一個'除了dns.resolver.DNSException'將是明智的,用於處理沒有特定處理的子例外(或者確保捕獲所有的dns錯誤)。 – 2013-12-02 08:55:56