How to catch a generic exception?

  • Thread starter Boogie El Aceitoso
  • Start date
B

Boogie El Aceitoso

Hi,

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

For example, something like this
try:
generateSomeException()
except e:
print e
 
G

Gonçalo Rodrigues

Hi,

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

First answer: don't try to do it, you'll get bitten by it.
For example, something like this
try:
generateSomeException()
except e:
print e

Second answer: The Exception class is the base class of all exception
classes. So, the following should work:

try:
<code goes here>
except Exception, e:
print e


Notice that you'll catch *every* exception, even a KeyboardInterrupt
(or whatever it's called) - are you sure that's what you want?

With my best regards,
G. Rodrigues
 
P

Peter Maas

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

For example, something like this
try:
generateSomeException()
except e:
print e

did you mean catch or throw?

--- catch:

try:
generateSomeException()
except Exception, e: # Mother of all exceptions
print e

--- throw:

try:
raise Exception, "Something is rotten in the state of Denmark"
except e:
print e
 
P

Peter Otten

Boogie said:
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:
.... 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:
.... raise KeyError
.... except:
.... print sys.exc_info()
....
.... raise "so what"
.... except:
.... print sys.exc_info()
....

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

Peter
 
P

Peter Maas

Peter said:
--- throw:

> try:
> raise Exception, "Something is rotten in the state of Denmark"
> except e:
> print e

Sorry, lazy copy. Correction:

try:
raise Exception, "Something is rotten in the state of Denmark"
except Exception, e:
print e

Mit freundlichen Gruessen,

Peter Maas
 

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,013
Latest member
KatriceSwa

Latest Threads

Top