Re: exceptions again?

Guido.van.Rossum@cwi.nl
Tue, 31 Jan 1995 00:20:01 +0100

> The first exception handler I coded was this:
>
> try:
> f = urllib.urlopen(url)
> except IOError, (error, msg):
> print error + ": " + msg
> return
>
> This worked great when the exception type thrown was a socket error (i.e.
> ('socket error', 'host not found')) or any one with only two members in the
> tuple.
>
> However, if I specify an unknown host, I get this message:
>
> ('http error', 404, 'Not Found', <Message instance at 3222ec>)
>
> and an error saying that the tuple unpacked to the wrong size -- this makes
> sense.
>
> My question is, how do I code the except such that I can handle and
> correctly identify each type of error appropriately?

If all you want is to print the error, you don't need to unpack it
into separate components at all: just do

try:
...
except IOError, msg:
print "I/O Error:", msg

Otherwise, you can use the type() and len() functions to detect what
kind of error data you have, e.g.

if type(msg) == type(()): # It's a tuple
if len(msg) == 2:
left, right = msg
print left, ":", right
elif len(msg) == 4:
errortype, errorcode, errormsg, messageobject = msg
if errorcode == 404:
...
etc.
else:
print msg # Tuple of other size
else:
print msg # Not a tuple

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>