在Python中使用isinstance检查特定类型的异常是否合理?

Vor*_*ura 10 python exception-handling introspection dnspython

在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"
Run Code Online (Sandbox Code Playgroud)

我是Python的新手,所以要温柔!

Sve*_*ach 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"
Run Code Online (Sandbox Code Playgroud)

注意子句的顺序:将采用第一个匹配子句,因此将超类的检查移到末尾.