Inventory of URLError and HTTPError exception handling methods

Inventory of URLError and HTTPError exception handling methods

[[390611]]

1. Introduction

This article mainly talks about URLError and HTTPError, as well as some processing methods.

2. URLError

1. Explain the three possible reasons for URLError:

  1. # 1. There is no network connection, that is, the machine cannot access the Internet.
  2.  
  3. # 2. Unable to connect to a specific server.
  4.  
  5. # 3. The server does not exist.

2. Case examples:

In the code, try-except statements are needed to surround and capture corresponding exceptions.

  1. # coding:UTF8
  2.  
  3. import urllib.request
  4.  
  5. request = urllib.request.urlopen( "http://www.baidu.com" )
  6.  
  7. try:
  8. urllib.request.urlopen(request)
  9. print( "[Errno 11004] getaddrinfo failed" )
  10. except urllib.URLError as e:
  11. print(e.reason)

The urlopen method was used to access a non-existent URL.

Running results:

Note:

It shows that the error code is 11004 and the error reason is getaddrinfo failed.

HTTPError

HTTPError is a subclass of URLError. When a request is made using the urlopen method, the server will have a corresponding response object, which contains a digital "status code".

example:

The caught exception is HTTPError, which has a code attribute, which is the error code, and a reason attribute, which is an attribute of its parent class URLError.

  1. import urllib2
  2. req = urllib2.Request( 'http://blog.csdn.net/cqcre' )
  3. try:
  4. urllib2.urlopen(req)
  5. except urllib2.HTTPError, e:
  6. print e.code
  7. print e.reason

Running results:

1. Code analysis

The error code is 403 and the error reason is Forbidden, which means the server prohibits access.

As we know, the parent class of HTTPError is URLError. According to programming experience, the exception of the parent class should be written after the child class exception. If the child class cannot catch it, then the parent class exception can be caught.

2. Optimize the code

  1. import urllib2
  2. req = urllib2.Request( 'http://blog.csdn.net/cqcre' )
  3. try:
  4. urllib2.urlopen(req)
  5. except urllib2.HTTPError, e:
  6. print e.code
  7. except urllib2.URLError, e:
  8. print e.reason
  9. else :
  10. print "OK"    

If HTTPError is caught, the code is output and the URLError exception is not processed. If a non-HTTPError occurs, the URLError exception is caught and the cause of the error is output.

In addition, you can add the hasattr attribute to judge the attribute in advance. The code is rewritten as follows

  1. import urllib2
  2. req = urllib2.Request( 'http://blog.csdn.net/cqcre' )
  3. try:
  4. urllib2.urlopen(req)
  5. except urllib2.URLError, e:
  6. if hasattr(e, "code" ):
  7. print e.code
  8. if hasattr(e, "reason" ):
  9. print e.reason
  10. else :
  11. print "OK"    

3. Exception handling method

First, judge the abnormal attributes to avoid attribute output errors.

If the response is a "redirect", you need to locate another address to get the document, urllib2 will handle this.

Note:

When an HTTPError instance is generated, it will have a code attribute, which is the relevant error number sent by the server.

Because urllib2 can handle redirects, that is, codes starting with 3 can be processed, and numbers in the range of 100-299 indicate success, so only error numbers 400-599 are seen.

IV. Conclusion

This article is based on the basics, through case analysis and code display. It solves the problem of handling URLError null exceptions in practical applications. It introduces two main exception errors and provides solutions to the corresponding errors.

Everyone is welcome to try actively. Sometimes it is easy to implement something when you see others do it, but when you try to implement it yourself, there will always be various problems. Don't be too ambitious and be diligent in doing it, so that you can understand it more deeply.

The use of language can make readers understand the content of the article more clearly and intuitively. The code is very simple, I hope it will be helpful for learning.

<<:  Facebook launches new AI project to learn from videos

>>:  Is the slowdown in the growth of China Mobile's 5G package users intentional, or are there other reasons?

Recommend

New threats to blockchain platforms

According to Huobi Blockchain Research Center, pe...

The emergence of 6G technology: growth opportunities for modern industry

The potential of 6G technology will become appare...

If these five gaps cannot be overcome, 5G 2B will be a pipe dream for operators

In the 5G race, Asian operators are among the wor...

165 million! China Mobile’s 5G user number announced, is 4G really outdated?

[[377452]] On January 20, China Mobile announced ...

4 major roles of the network in enterprise digital transformation

Currently, digital transformation is described as...

In-depth analysis of SSL digital certificates to protect corporate websites

An SSL certificate is a type of digital certifica...

Learn Network TCP/IP Protocol Stack

[[409633]] This article is reprinted from the WeC...

Remember who was to blame for a thread pool-induced fault?

This article is reproduced from the WeChat public...

5G without "it" is like building a house without land

As a city's population continues to grow, it ...