gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:18:49 25 4
gpt4 key购买 nike

在 Python 中捕获一般异常,然后使用 isinstance() 检测特定类型的异常以便适本地处理它是否合理?

我目前正在使用 dnspython 工具包,它有一系列异常,例如超时、NXDOMAIN 响应等。这些异常是 dns.exception.DNSException 的子类>,所以我想知道捕获 DNSException 然后使用 isinstance() 检查特定异常是否合理或 pythonic。

例如

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"

注意子句的顺序:将采用第一个匹配的子句,因此将父类(super class)的检查移到末尾。

关于python - 在 Python 中使用 isinstance 检查特定类型的异常是否合理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9245067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com