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

exception handling

P: n/a
Hello,
def error_msg(msg):
sys.exit(msg)

try:
do_something()
if value != my_wish:
error_msg('Invalid input')
except:
print "Fatal IO or Network error"

This doesn't work because sys.exit raises an exception.

I know that I can define exception types after except, but there might
be many. Also I know I can write:
except:
if str(sys.exc_info()[0]) == 'exceptions.SystemExit':
raise

But honestly I would like simething like that:

except (!SystemExit):

Is this possible somehow?

Mage
Jul 19 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Mage wrote:
def error_msg(msg):
sys.exit(msg)

try:
do_something()
if value != my_wish:
error_msg('Invalid input')
except:
print "Fatal IO or Network error"

This doesn't work because sys.exit raises an exception.

I know that I can define exception types after except, but there might
be many. Also I know I can write:
except:
if str(sys.exc_info()[0]) == 'exceptions.SystemExit':
raise

But honestly I would like simething like that:

except (!SystemExit):

Is this possible somehow?


try:
# may raise any exception
except SystemExit:
raise # propagate SystemExit (and subclasses)
except:
# handle everything else

Peter

Jul 19 '05 #2

P: n/a
Mage <ma**@mage.hu> wrote:
Hello,
def error_msg(msg):
sys.exit(msg)

try:
do_something()
if value != my_wish:
error_msg('Invalid input')
except:
print "Fatal IO or Network error"

This doesn't work because sys.exit raises an exception.


Peter Otten posted a good way to do what you want, but I'm not convinced
that it's a good idea.

You're assuming that any exception you get will be a "Fatal IO or Network
error". What if it's not? What if do_something() raises FutureWarning, or
KeyboardInterrupt, or AssertionError, or DeprecationWarning, or anything
else which has nothing to do with IO or networks? You would just end up
producing a misleading error message.

If you expect do_something() will throw certain exceptions, catch them
specifically. It's usually a mistake to catch everything. It's certainly
a mistake to catch everything and assume you know what it must be.

Try running the following code and see what happens:

import traceback

def do_something():
pass

try:
do_something()
if value != my_wish:
error_msg('Invalid input')
except:
print "Fatal IO or Network error"
print traceback.print_exc()
Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.