如何知道在python中捕获哪种异常类型?

时间:2012-11-07 09:29:16

标签: python exception types

一般异常捕获器记录以下异常:

> Traceback (most recent call last):   File "4sq.py", line 37, in
> <module>
>     checkin = client.checkins()   File "/usr/local/lib/python2.7/dist-packages/foursquare-20120716-py2.7.egg/foursquare/__init__.py",
> line 416, in __call__
>     return self.GET('{CHECKIN_ID}'.format(CHECKIN_ID=CHECKIN_ID), params, multi=multi)   File
> "/usr/local/lib/python2.7/dist-packages/foursquare-20120716-py2.7.egg/foursquare/__init__.py",
> line 217, in GET
>     return self.requester.GET(self._expanded_path(path), *args, **kwargs)   File "/usr/local/lib/python2.7/dist-packages/foursquare-20120716-py2.7.egg/foursquare/__init__.py",
> line 163, in GET
>     return self._request(url)   File "/usr/local/lib/python2.7/dist-packages/foursquare-20120716-py2.7.egg/foursquare/__init__.py",
> line 200, in _request
>     return _request_with_retry(url, data)['response']   File "/usr/local/lib/python2.7/dist-packages/foursquare-20120716-py2.7.egg/foursquare/__init__.py",
> line 696, in _request_with_retry
>     return _process_request_with_httplib2(url, data)   File "/usr/local/lib/python2.7/dist-packages/foursquare-20120716-py2.7.egg/foursquare/__init__.py",
> line 719, in _process_request_with_httplib2
>     return _check_response(data)   File "/usr/local/lib/python2.7/dist-packages/foursquare-20120716-py2.7.egg/foursquare/__init__.py",
> line 742, in _check_response
>     raise exc(meta.get('errorDetail')) RateLimitExceeded: Quota exceeded

我想知道具体的异常名称,所以我可以添加一个专用的catch。 怎么能找到它?

在捕获的异常上是否有'type'函数,或者是否应该在throw lib的源代码中找到它 - 可用here

2 个答案:

答案 0 :(得分:3)

这本来是一个评论,但由于它得到了很多赞成,并且OP声称这是他们正在寻找的东西,我将它作为答案重新发布:

看起来它是一个RateLimitExceeded异常。但是,如果你真的想确定,你可以这样做:

try:
    # code
except Exception as e:
    print e.__class__

这将打印出引发的异常类,这将为您提供明确的答案

答案 1 :(得分:2)

粘贴中引发的异常是foursquare.RateLimitExceeded(如最后一行所示)。您应该能够正常捕获它,或者如果要处理模块中的所有错误,则捕获其基类foursquare.FoursquareException

引发异常的代码只是查找从字典中引发的异常类。这不应该对你如何捕获这些错误产生任何影响。