try/except/finally construct not available?

Ian Sparks Ian.Sparks at etrials.com
Tue Jun 29 15:21:22 CEST 2004


> 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();
> }

In python you need an extra try..finally around your try..except

try:
    try:
        a.mightThrow()
    except:
	print "Looks like an exception"
finally
   a.cleanup()

you can also have multiple except clauses to handle different types of exception :

try:
    try:
        a.mightThrow()
    except KeyError:
        print "Looks like a KeyError"
    except:
        print "Looks like some other sort of exception"
finally
   a.cleanup()

> -----Original Message-----
> From: Christopher Baus [mailto:christopher at baus.net]
> Sent: Monday, June 28, 2004 4:00 PM
> To: python-list at python.org
> Subject: try/except/finally construct not available?
> 
> 
> 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.
> 
> 
> 
> -- 
> Christopher Baus
> http://www.baus.net/
> Tahoe, Wine, and Linux.
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 




More information about the Python-list mailing list