NameError: global name 'HTTPError' is not defined

后端 未结 4 1550
说谎
说谎 2021-01-04 01:16

I have a command in a try clause which I know throws an exception. I\'m trying to catch it in an \"except\" clause, but the except clause seems to not recognize the existen

相关标签:
4条回答
  • 2021-01-04 01:40

    In Python 3 it's:

    from urllib.error import HTTPError
    
    0 讨论(0)
  • 2021-01-04 01:42

    You need to check for urllib2.HTTPError:

    except urllib2.HTTPError:
    
    0 讨论(0)
  • 2021-01-04 01:53

    You probably just need to import the HTTPError class before using it. Try inserting at the top of your actions.py file:

    from urllib2 import HTTPError
    

    and then you should be able to use your code as is.

    0 讨论(0)
  • 2021-01-04 02:07

    @Emily's solution is fine, but there's another way to solve this problem without importing that class.

    You just need to give the full name space of the exception class you want to catch:

    except urllib2.HTTPError:
    

    This way you need fewer import clauses in your code, and it's easier for you to tell afterwards which module raised the exception.

    0 讨论(0)
提交回复
热议问题