How to except the unexpected?
Roy Smith
roy at panix.com
Sat Mar 4 07:34:42 EST 2006
Rene Pijlman <reply.in.the.newsgroup at my.address.is.invalid> wrote:
> A catchall seems like a bad idea, since it also catches AttributeErrors
> and other bugs in the program.
All of the things like AttributeError are subclasses of StandardError. You
can catch those first, and then catch everything else. In theory, all
exceptions which represent problems with the external environment (rather
than programming mistakes) should derive from Exception, but not from
StandardError. In practice, some very old code may raise things which do
not derive from Exception, which complicates things somewhat.
--------------------------------------------------
#!/usr/bin/env python
import socket
try:
x = []
y = x[42]
except StandardError, foo:
print "Caught a StandardError: ", foo
except Exception, foo:
print "Caught something else: ", foo
try:
socket.socket (9999)
except StandardError, foo:
print "Caught a StandardError: ", foo
except Exception, foo:
print "Caught something else: ", foo
try:
raise "I'm a string pretending to be an exception"
except StandardError, foo:
print "Caught a StandardError: ", foo
except Exception, foo:
print "Caught something else: ", foo
--------------------------------------------------
Roy-Smiths-Computer:play$ ./ex.py
Caught a StandardError: list index out of range
Caught something else: (43, 'Protocol not supported')
Traceback (most recent call last):
File "./ex.py", line 21, in ?
raise "I'm a string pretending to be an exception"
I'm a string pretending to be an exception
More information about the Python-list
mailing list