newbie question about confusing exception handling in urllib
Ian Kelly
ian.g.kelly at gmail.com
Tue Apr 9 15:11:18 EDT 2013
On Tue, Apr 9, 2013 at 5:41 AM, <cabbar at gmail.com> wrote:
> try:
> response = urllib.request.urlopen(request)
> content = response.read()
> except BaseException as ue:
> if (isinstance(ue, socket.timeout) or (hasattr(ue, "reason") and isinstance(ue.reason, socket.timeout)) or isinstance(ue, ConnectionResetError)):
> print("REQUEST TIMED OUT")
I'm surprised nobody has yet pointed out that you can catch multiple
specific exception types in the except clause rather than needing to
organize them under a catch-all base class. These two code blocks are
basically equivalent:
try:
do_stuff()
except BaseException as ue:
if isinstance(ue, (socket.timeout, ConnectionResetError)):
handle_it()
else:
raise
try:
do_stuff()
except (socket.timeout, ConnectionResetError) as ue:
handle_it()
Cheers,
Ian
More information about the Python-list
mailing list