catch specific HTTP error in python

前端 未结 3 1808
半阙折子戏
半阙折子戏 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:47

    Tims answer seems to me as misleading. Especially when urllib2 does not return expected code. For example this Error will be fatal (believe or not - it is not uncommon one when downloading urls):

    AttributeError: 'URLError' object has no attribute 'code'

    Fast, but maybe not the best solution would be code using nested try/except block:

    import urllib2
    try:
        urllib2.urlopen("some url")
    except urllib2.HTTPError, err:
        try:
            if err.code == 404:
                # Handle the error
            else:
                raise
        except:
            ...
    

    More information to the topic of nested try/except blocks Are nested try/except blocks in python a good programming practice?

提交回复
热议问题