Question about exception-handling mechanism

Carel Fellinger cfelling at iae.nl
Tue Apr 25 19:24:03 EDT 2000


willfg at my-deja.com wrote:
> Hello all,

> colleague asked why in an exception handling mechanism you'd want the
> ELSE block to be executed if you don't throw an exception as opposed to
> a FINALLY block. Anyone used this feature in practice? Thanks in
> advance for your input, -- Will

others have given a more abstract anwser, but being in a talkative mood
I'll try to add a real example:)

>>> open_connection_to_other_computer_via_the_phone()
>>> try:
>>>     do_something_worthwile()
>>> finally:
>>>     #to avoid extreme bills we have to hang-up no matter what
>>>     close_connection_and_hang_up_the_phone()

the finally clause here is the obvious way to guarantee that the phone
is put on the hook, even if some unexpected exception occurred and the
program is really dying. Ofcourse you can approach the same with a cach-all

>>> except:
>>>     close_connection_and_hang_up_the_phone()
>>>     raise   #reraise the current exception

But somehow this is deemed inferior and less clear then the above.
(Funny if you think of the down-out horrible
but widely defended while 1:...break idiom:)

>>> dict = {1: "the time is 1:30", 2: "the time is 2:45"}
>>> try:
>>>     time_string = dict[1]
>>> except KeyError:
>>>     t = some_default_time_value_not_needing_convertion_from_string
>>> else:
>>>     t = extract_time_from_string(time_string)

Again this can easily be achieved in different ways in this example.


ceterum censeo
    while: ... break
should have been part of the language to begin with
-- 
groetjes, carel



More information about the Python-list mailing list