errors and exception

Gary Herron gherron at islandtraining.com
Mon Aug 16 09:29:26 CEST 2010


On 08/16/2010 12:06 AM, Alan wrote:
> Hello,
>
> I am using things like:
> except  Exception  as  inst:
> and

The old syntax for exceptions still works in Python2.x (all versions).  
The new syntax works in Python2.6+  and Python3.

     try:
         whatever
     except Exception,msg:  # Old syntax
         print msg


>
>
> with  open("myfile.txt")  as  f:
>      for  line  in  f:
>          print  line


You don't need the new fangled with statement if you want to be 
compatible with older versions of Python2.  (It's nice and convenient, 
but not necessary.)

f = open("myfile.txt")
for line in f:
   print line
f.close()   # This is what the "with" statement guarantees; so now just 
do it yourself


Gary Herron



> Things that seems to be new in python 2.6 and higher, however reading 
> http://docs.python.org/tutorial/errors.html and this not clear when 
> this new syntaxes appeared.
>
> My trouble is that I want to make something similar above compatible 
> with python 2.5, but when running python2.5 I got:
>
> except Exception as msg:
>                       ^
> SyntaxError: invalid syntax
> If there's a way (e.g. from __future__ ..., inherited modified 
> Exception class, etc) that could give a solution to keep my code in 
> python 2.6 syntax as above but compatible with python 2.5, that would 
> be appreciated.
>
> Many thanks in advance,
>
> Alan
> -- 
> Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
> Department of Biochemistry, University of Cambridge.
> 80 Tennis Court Road, Cambridge CB2 1GA, UK.
> >>http://www.bio.cam.ac.uk/~awd28 <http://www.bio.cam.ac.uk/%7Eawd28><<

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100816/bbe1612a/attachment.html>


More information about the Python-list mailing list