Exception handling....dumb question?
Felipe Almeida Lessa
felipe.lessa at gmail.com
Sun Apr 2 09:08:00 EDT 2006
Em Dom, 2006-04-02 às 15:54 +0300, Flexx escreveu:
> Ben Finney writes:
> > This allows all other exceptions to propogate back through the call
> > stack.
>
> import sys, logging
> try:
> foo = 12/0
> except:
> e = str(sys.exc_value)
> print "You *knew* this was going to happen: '%s'" % (e)
> logging.error(e)
The point (I think) Ben was trying to show is that you should not hide
exceptions from the caller's code unless you expected that exception.
For example:
def percentage(now, total):
"""Returns the percentage of now in total."""
return now * 100.0 / total
Very simple. What if I do "percentage(1, 0)"? The code expected me to be
clever enough to know that you can't make a percentage when the total is
zero, so it lets the exception pass by to my code (like: "it's your
problem, not mine!"):
>>> percentage(1, 0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in percentage
ZeroDivisionError: float division
But if your function is being used on a context where total can be zero
and it has a meaning, for example, returning -1, then _in_this_case_ you
should catch the exception:
def percentage(now, total):
"""Returns the percentage of now in total.
If total is zero, then return -1.
"""
try:
return now * 100.0 / total
except ZeroDivisionError:
return -1
>>> percentage(1, 0)
-1
But this function won't catch exceptions if you don't give it numbers:
>>> percentage(None, 1)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 7, in percentage
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'
But this is also a problem on the caller's code! You should *not* hide
it from him! But if None is valid in the context of your code, then...
well, you get the point! =)
HTH,
--
Felipe.
More information about the Python-list
mailing list