How to catch a generic exception?

Peter Otten __peter__ at
Thu Mar 4 17:19:07 CET 2004

Boogie El Aceitoso wrote:

> How can I catch a generic exception (without knowing a priori what
> exception it will be)?

If you catch the generic Exception, there is a small chance that your except
suite will be bypassed:

>>> try:
...     raise "yes, it's deprecated"
... except Exception, e:
...     print "will we ever see this?"
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
yes, it's deprecated

This seems to work:

>>> try:
...     raise KeyError
... except:
...     print sys.exc_info()
(<class exceptions.KeyError at 0x4024892c>, <exceptions.KeyError instance at
0x40290d0c>, <traceback object at 0x4028f414>)
>>> try:
...     raise "so what"
... except:
...     print sys.exc_info()
('so what', None, <traceback object at 0x4028f324>)

Not very elegant though. But then, not knowing what to catch is something
that should be avoided in the first place.


More information about the Python-list mailing list