[Q] Are Exceptions used that much in practice?
Rainer Deyke
root at rainerdeyke.com
Tue Dec 12 22:07:17 EST 2000
"Jerome Mrozak" <goose at enteract.com> wrote in message
news:3A36C6E3.26181E3F at enteract.com...
> I believe I've been misunderstood. The problem is not "can I write code
> without handling exceptions" but rather "are exceptions used
> voluntarily, rather than by compulsion".
The Python interpreter will throw exceptions. You are not obligated to
handle them. In some cases, you can prevent the exception from being thrown
in the first place.
For example, suppose you are trying to calculate the average of a sequence.
def average(l):
total = 0
for item in l:
total += item
total /= len(l)
When the length of the sequence is 0, this throws a ZeroDivisionError. You
can handle this with a try clause:
def average(l):
total = 0
for item in l:
total += item
try:
total /= len(l)
except ZeroDivisionError:
return 0
You can handle it with a guard condition:
def average(l):
total = 0
for item in l:
total += item
if len(l) == 0:
return 0
else:
return total / len(l)
Or you can ignore it altogether, assuming that you will never be passed an
empty sequence:
def average(l):
total = 0
for item in l:
total += item
total /= len(l)
This last option is actually the best in most cases. If the caller wants to
pass an empty sequence, the caller still has the option of catching the
ZeroDivisionError:
try:
avg = average([])
except ZeroDivisionError:
print 'Hello world!'
--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games - http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor
More information about the Python-list
mailing list