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?).
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With