exception handling
Roy Smith
roy at panix.com
Wed Apr 20 09:32:04 EDT 2005
Mage <mage at 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()
More information about the Python-list
mailing list