如何引发 HTTPError

How to raise HTTPError

测试一些使用 urllib2, I want to raise an HTTPError 的代码以确保它被正确处理。

HTTPError 有一个构造函数:

def __init__(self, url, code, msg, hdrs, fp):

我不知道要传递什么作为最后一个参数fp

你能帮我举个例子吗HTTPError raise HTTPError('arg1','arg2','arg3','arg4',...

如何做到?

通过 fp=None.

来自source code

# The addinfourl classes depend on fp being a valid file
# object.  In some cases, the HTTPError may not have a valid
# file object.  If this happens, the simplest workaround is to
# not initialize the base classes.
if fp is not None:
    self.__super_init(fp, hdrs, url, code)

fp 需要是一个类似文件的对象,因此如果您愿意,可以传递一个 StringIO 对象。