exception handling

M

Mage

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
 
P

Peter Otten

Mage said:
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
 
R

Roy Smith

Mage said:
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()
 

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

Forum statistics

Threads
474,235
Messages
2,571,181
Members
47,818
Latest member
KazukoXea6

Latest Threads

Top