thinker3
thinker3

Reputation: 13301

How to catch all the exceptions but someone in python?

I want to catch all the exceptions but someone, e.g. KeyboardInterrupt,

the following is part of my code:

try:
    num = 70
    while 1:
        print 'hello %d' % num
        sleep(0.1)
        num += 1
        a = 1/(num - 80)
except not KeyboardInterrupt:
        print 'ctrl c'
        save(num)

It does not work.

Upvotes: 0

Views: 101

Answers (2)

Catch and re-raise it before the general case

try:
    #stuff
except KeyboardInterrupt:
    raise #rethrow to a higher handler
except:
    #everything else

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

If you are happy with also not catching SystemExit and StopIteration, just do

except Exception:

because that only catches "higher-level" exceptions. Still, this is considered bad practice. Always be specific in catching exceptions.

Upvotes: 2

Related Questions