在 t.cursor() 方法中,Twython 库中的一小部分 id 会引发异常。但是,无论何时发生异常,在我的代码中引发异常的实际行是 try/except 块之后的 for 循环,这会阻止continue
调用 。
如何在 try 块中抛出异常,而不是被 except 块捕获,然后在一些(大部分)不相关的代码中出现?
是的,这是一个 401 错误,但这只是 Twitter API 返回错误代码。实际上,我正确地进行了身份验证。我也知道我可以将 except 块移到 for 循环之后,但我只想知道这到底是怎么发生的。
from twython import Twython
t = Twython(...)
# ...
for id in ids:
try:
# exception is truly caused by the following line
followers = t.cursor(t.get_followers_ids, id=id)
except:
# this block is never run
print("Exception with user " + str(id))
continue
# this line actually throws the exception, inexplicably
for follower_id in followers:
values.append((follower_id, id, scrape_datetime))
# ...
追溯:
Traceback (most recent call last):
File "/root/twitter/nightly.py", line 5, in <module>
t.get_followers(t.current_tweeters)
File "/root/twitter/tweets.py", line 81, in get_followers
for follower_id in followers:
File "/usr/local/lib/python3.3/dist-packages/twython-3.0.0-py3.3.egg/twython/api.py", line 398, in cursor
content = function(**params)
File "/usr/local/lib/python3.3/dist-packages/twython-3.0.0-py3.3.egg/twython/endpoints.py", line 212, in get_followers_ids
return self.get('followers/ids', params=params)
File "/usr/local/lib/python3.3/dist-packages/twython-3.0.0-py3.3.egg/twython/api.py", line 231, in get
return self.request(endpoint, params=params, version=version)
File "/usr/local/lib/python3.3/dist-packages/twython-3.0.0-py3.3.egg/twython/api.py", line 225, in request
content = self._request(url, method=method, params=params, api_call=url)
File "/usr/local/lib/python3.3/dist-packages/twython-3.0.0-py3.3.egg/twython/api.py", line 195, in _request
retry_after=response.headers.get('retry-after'))
twython.exceptions.TwythonAuthError: Twitter API returned a 401 (Unauthorized), An error occurred processing your request.