[Tutor] question regarding python exception handling

Alan Gauld alan.gauld at freenet.co.uk
Sun Jan 30 11:05:37 CET 2005


> a Nutshell". In the chapter of exception handling, it says: Note
that
> the try/finally form is distinct from the try/except form: a try
> statement cannot have both except and finally clauses, as execution
> order might be ambiguous.
>
> I don't understand the reason why except and finally clauses cannot
be
> together. I know they can be together in java. how does it cause
> ambiguous execution order? An example may help me understand.

To be honest I've never quite worked this out either.
But it's what the language does so I don't lose sleep
about it.

Instead of

try:
  # some code
except anException:
  # some more code
finally:
  # tidy up now

Just do:

try:
  try:
    # some code
  except anException:
    # some more code
finally:
 # tidy up now.

For the cost of 4 extra characters and some whitespace I
can live with it! :-)

FWIW Delphi does exactly the same.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list