[Tutor] Exception handling - syntaxerror?!

ZIYAD A. M. AL-BATLY zamb at saudi.net.sa
Sun Sep 25 16:08:07 CEST 2005


On Sun, 2005-09-25 at 18:55 +0530, Krishna wrote:
> When I try to run the following piece of code, I get a SyntaxError,
> can someone help me out on this?
> 
> try:
> ... 	os.system("cls")
> ... except:
> ... 	print "Foo"
> ... print "Bar"
> Traceback (  File "<interactive input>", line 5
>     print "Bar"
>         ^
> SyntaxError: invalid syntax
> 
> What am I missing?
> 
> Thanks in advance,
> Kris
What you're writing is this:
        try:
          os.system("cls")
            except:
              print "Foo"
            print "Bar"

Which is wrong!  Here's the correct way:
        try:
          os.system("cls")
        except:
          print "Foo"
        print "Bar"


Note the indentation for "try:" and "except:"?  They most be on the same
level.  This is how exception handling is done in Python.

By the way, the last "print" statement, I didn't know if you want it to
be printed all the time (like what I wrote it above) or just when
there's an exception.

Ziyad.



More information about the Tutor mailing list