How to Catch 2 Exceptions at once?

  • Thread starter =?ISO-8859-1?Q?Gregory_Pi=F1ero?=
  • Start date
?

=?ISO-8859-1?Q?Gregory_Pi=F1ero?=

How can I catch 2 exceptions at once for example:

try:
self.gses = opener.open(req)
except (urllib2.HTTPError,urllib2.URLError):
do something..

Seems to work, but how do I also get information about the error?
 
J

James Stroud

Gregory said:
How can I catch 2 exceptions at once for example:

try:
self.gses = opener.open(req)
except (urllib2.HTTPError,urllib2.URLError):
do something..

Seems to work, but how do I also get information about the error?
py> try:
.... raise ValueError, 'Illegal value for your shoe size!'
.... except (IndexError, ValueError), e:
.... print e
....
Illegal value for your shoe size!


--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
 
J

John Machin

Gregory said:
How can I catch 2 exceptions at once for example:

try:
self.gses = opener.open(req)
except (urllib2.HTTPError,urllib2.URLError):
do something..

Seems to work, but how do I also get information about the error?

Errr .. the same way as if you mentioned only one exception. The
following is an expansion of the scarcely-describable-as-bare coverage
in the tutorial
(http://docs.python.org/tut/node10.html#SECTION0010300000000000000000):

C:\junk>cat gregpexc.py
import sys
try:
fname = raw_input('File name:')
f = open(fname)
i = 1 / 0
# except IOError, (errno, strerror):
# print "I/O error(%s): %s" % (errno, strerror)
except (IOError, KeyboardInterrupt, ZeroDivisionError), e :
print repr(e)
print e
print dir(e)
print e.args
print e.__class__.__name__
except:
print "Unexpected error:", sys.exc_info()[0]
# no example shown; read the fine manual :)
raise

C:\junk>python gregpexc.py
File name:<exceptions.KeyboardInterrupt instance at 0x00AF1EE0>

['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args']
()
KeyboardInterrupt

C:\junk>python gregpexc.py
File name:kl;lklklklk
<exceptions.IOError instance at 0x00AF1F08>
[Errno 2] No such file or directory: 'kl;lklklklk'
['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args',
'errno',
'filename', 'strerror']
(2, 'No such file or directory')
IOError

C:\junk>python gregpexc.py
File name:gregpexc.py
<exceptions.ZeroDivisionError instance at 0x00AF1F08>
integer division or modulo by zero
['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args']
('integer division or modulo by zero',)
ZeroDivisionError

HTH,
John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top