问题:在 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 新手,所以要温柔!

解答

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

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

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐