Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I catch a specific HTTP error in Python?

I have

import urllib2 try:    urllib2.urlopen("some url") except urllib2.HTTPError:    <whatever> 

but what I end up is catching any kind of HTTP error. I want to catch only if the specified webpage doesn't exist (404?).

like image 491
Arnab Sen Gupta Avatar asked Jul 07 '10 08:07

Arnab Sen Gupta


People also ask

How do you catch specific errors in Python?

Catching Specific Exceptions in PythonA try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an exception occurs. We can use a tuple of values to specify multiple exceptions in an except clause.

How does Python handle HTTP errors?

Just catch HTTPError , handle it, and if it's not Error 404, simply use raise to re-raise the exception. See the Python tutorial. can i do urllib2. urlopen("*") to handle any 404 errors and route them to my 404.

What is HTTPError Python?

HTTPError. Though being an exception (a subclass of URLError ), an HTTPError can also function as a non-exceptional file-like return value (the same thing that urlopen() returns). This is useful when handling exotic HTTP errors, such as requests for authentication. code. An HTTP status code as defined in RFC 2616.

How do you raise the HTTP exception in Python?

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception. In the rare event of an invalid HTTP response, Requests will raise an HTTPError exception. If a request times out, a Timeout exception is raised.


1 Answers

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.

Here is a complete example for Python 2:

import urllib2 from urllib2 import HTTPError try:    urllib2.urlopen("some url") except HTTPError as err:    if err.code == 404:        <whatever>    else:        raise 
like image 197
Tim Pietzcker Avatar answered Oct 13 '22 04:10

Tim Pietzcker