By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,846 Members | 1,862 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,846 IT Pros & Developers. It's quick & easy.

How to Catch 2 Exceptions at once?

P: n/a
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?

--
Gregory Piñero
Chief Innovation Officer
Blended Technologies
(www.blendedtechnologies.com)
Oct 1 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Gregory Piñero wrote:
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?
pytry:
.... 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/
Oct 1 '06 #2

P: n/a

Gregory Piñero wrote:
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.ht...000000000000):

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

Oct 1 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.