Handling urllib2's timeout? - Python
There are very few cases where you want to use except:
. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit
and KeyboardInterupt
, which can make your program annoying to use..
At the very simplest, you would catch urllib2.URLError
:
try: urllib2.urlopen("http://example.com", timeout = 1)except urllib2.URLError, e: raise MyException("There was an error: %r" % e)
The following should capture the specific error raised when the connection times out:
import urllib2import socketclass MyException(Exception): passtry: urllib2.urlopen("http://example.com", timeout = 1)except urllib2.URLError, e: # For Python 2.6 if isinstance(e.reason, socket.timeout): raise MyException("There was an error: %r" % e) else: # reraise the original error raiseexcept socket.timeout, e: # For Python 2.7 raise MyException("There was an error: %r" % e)
In Python 2.7.3:
import urllib2import socketclass MyException(Exception): passtry: urllib2.urlopen("http://example.com", timeout = 1)except urllib2.URLError as e: print type(e) #not catchexcept socket.timeout as e: print type(e) #catched raise MyException("There was an error: %r" % e)