try/except/finally construct not available?

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Mon Jun 28 22:12:00 CEST 2004


Christopher Baus wrote:
> Hi,
> 
> I'm just learning python after years of C/C++/Java/bash/etc.  It is going
> pretty good except a few minor issues regarding syntax.  I have to admit
> the while/else contruct is a bit weird, but I think I understand the
> motivation.  But I am confused about exceptions having read the chapter in
> Learning Python.
> 
> How do I do something similar to the following java code?
> 
> try{
>   a.mightThrow();
> }
> catch(Exception e){
>   System.out.print("looks like an exception");
> }
> finally{
>   a.cleanup();
> }
> 
> try:
>    pass
> finally:
>    pass
> 
> Doesn't allow the programmer to catch certain exceptions, handle them, and
> then perform operations in either case.

This is, unfortunately, a FAQ:

You must use

try:
    try:
        <statements>
    except WhatEver:
        <statements>
finally:
    <statements>

This is due to the fact that try-except and try-finally are two
different constructs; there was a thread here not long ago, starting
with Message-ID <mailman.30.1087503791.18066.python-list at python.org>
(if you use a news server to access comp.lang.python).

Reinhold

-- 
Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows
mitbrächte, wäre das bedauerlich.  Was bei Windows der Umfang eines
"kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk.
  -- David Kastrup in de.comp.os.unix.linux.misc



More information about the Python-list mailing list