【问题标题】:Checking condition while Exception handling in python在python中处理异常时检查条件
【发布时间】:2014-08-21 17:01:14
【问题描述】:

这是我在 python 中的代码的一部分。我想检查错误消息,如果是HTTPError(),那么我想将主机添加到文件 ok.t​​xt 中。但它不起作用。这里有什么问题?

except urllib2.URLError, e:
        print '%-15s\t%15r' % (url.strip(), e)
        if e == 'HTTPError()':
            OK.write('%-15s' % (url.strip()) + '\n')
            OK.flush()

当我运行整个脚本时,输出是这样的:

http://a.com        HTTPError()
http://b.com    URLError(timeout('timed out',),)
http://c.com    URLError(timeout('timed out',),)
http://d.com    URLError(error(111, 'Connection refused'),)
http://e.com           200

【问题讨论】:

    标签: python exception if-statement exception-handling conditional-statements


    【解决方案1】:

    使用isinstance() 检查您的错误是否属于HTTPError 类型:

    except urllib2.URLError as e: # use the "as e" instead of the old style comma delimitation.
        print '%-15s\t%15r' % (url.strip(), e)
        if isinstance(e, HTTPError):
            OK.write('%-15s' % (url.strip()) + '\n')
            OK.flush()
    

    【讨论】:

    • 因为HTTPError()调用异常类。实际上,它会创建一个新的异常对象,但不会引发它。 HTTPError 是您可以检查的类型。
    • 谢谢...我正在检查您的解决方案
    猜你喜欢
    • 2011-02-13
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    相关资源
    最近更新 更多