catch specific HTTP error in python

前端 未结 3 1821
半阙折子戏
半阙折子戏 2020-11-30 22:15

I want to catch a specific http error and not any one of the entire family.. what I was trying to do is --

import urllib2
try:
   urllib2.urlopen(\"some url\         


        
3条回答
  •  孤街浪徒
    2020-11-30 22:53

    Python 3

    from urllib.error import HTTPError
    

    Python 2

    from urllib2 import HTTPError
    

    Just catch HTTPError, handle it, and if it's not Error 404, simply use raise to re-raise the exception.

    See the Python tutorial.

    e.g. complete example for Pyhton 2

    import urllib2
    from urllib2 import HTTPError
    try:
       urllib2.urlopen("some url")
    except HTTPError as err:
       if err.code == 404:
           
       else:
           raise
    

提交回复
热议问题