除了ValueError没有触发

时间:2017-01-17 18:03:57

标签: python

我正在调用外部API(这是私有的,所以我无法共享它)。出于某种原因,有时API会给我一个HTTPError,有时它会返回一些与我的其余代码不兼容的东西,这会引发ValueError

for row in dataset.iter_rows():
    saved = True
    while saved:
        url = "http://api.website.com/rest/v3/search?id={0}&profile=large&format=json".format(row["id_to_search"]) 
        try:
            r = urllib2.urlopen(url).read()
            result = json.loads(r)
            saved=False
            print result
        except urllib2.HTTPError: 
            print "too fast, waiting before retry"
            time.sleep(3)
        except ValueError:
            print "################ ValueError ################"
            time.sleep(5)
        time.sleep(0.5)

但是,如果我再次运行我的代码,则ValueError不再针对同一行引发:它似乎是随机出现的。这就是为什么我试图抓住它,等待,然后再试一次(见上面的代码),但......:

ValueError                                Traceback (most recent call last)
<ipython-input-19-3ae7644de1fc> in <module>()
     16         try:
     17             r = urllib2.urlopen(url).read()
---> 18             result = json.loads(r)
     19             saved=False
     20             print result

/usr/lib64/python2.7/json/__init__.pyc in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    336             parse_int is None and parse_float is None and
    337             parse_constant is None and object_pairs_hook is None and not kw):
--> 338         return _default_decoder.decode(s)
    339     if cls is None:
    340         cls = JSONDecoder

/usr/lib64/python2.7/json/decoder.pyc in decode(self, s, _w)
    363 
    364         """
--> 365         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    366         end = _w(s, end).end()
    367         if end != len(s):

/usr/lib64/python2.7/json/decoder.pyc in raw_decode(self, s, idx)
    381             obj, end = self.scan_once(s, idx)
    382         except StopIteration:
--> 383             raise ValueError("No JSON object could be decoded")
    384         return obj, end

ValueError: No JSON object could be decoded

......它没有被抓住。知道为什么吗?

1 个答案:

答案 0 :(得分:2)

您已将其他值指定为ValueError

MCVE:

import json
ValueError = None
try:
    json.loads("")
except ValueError:
    pass

没有发现异常:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\Python27\lib\json\__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded