14

I wrote a method that does some stuff and catches bad filenames. what should happen is if the path doesn't exist, it throws an IOError. however, it thinks my exception handling is bad syntax... why??

def whatever():
    try:
        # do stuff
        # and more stuff
    except IOError:
        # do this
        pass
whatever()

but before it even gets to calling whatever(), it prints the following:

Traceback (most recent call last):
  File "", line 1, in 
  File "getquizzed.py", line 55
    except IOError:
         ^
SyntaxError: invalid syntax

when imported...help?!

0

4 Answers 4

10

Check your indenting. This unhelpful SyntaxError error has fooled me before. :)

From the deleted question:

I'd expect this to be a duplicate, but I couldn't find it.

Here's Python code, expected outcome of which should be obvious:

x = {1: False, 2: True} # no 3

for v in [1,2,3]:
  try:
      print x[v]
  except Exception, e:
      print e
      continue
I get the following exception: SyntaxError: 'continue' not properly in loop.

I'd like to know how to avoid this error, which doesn't seem to be 
explained by the continue documentation.

I'm using Python 2.5.4 and 2.6.1 on Mac OS X, in Django.

Thank you for reading
Sign up to request clarification or add additional context in comments.

2 Comments

@tekknalogi: How do you know it won't? What error message are you getting?
Unfortunately, the link does not exist any more. Care to explain what the problem was?
5

there's 1 more possible if you're privileged to have an older installation

and

you're using the 'as' syntax:

     except IOError as ioe:

and

the parser's getting tripped up on 'as'.

Using as is the preferred syntax in Python 2.6 and better.

It's a syntax error in Python 2.5 and older. For pre-2.6, use this:

     except IOError, ioe:

Comments

2

Just missing something in your try block, i.e. pass or anything, otherwise it gives an indentation error.

Comments

1

You will get a syntax error if you don't put something in side the try block. You can put pass just to hold the space:

try:
    # do stuff
    # and more stuff
    pass
except IOError:
    # do this
    pass

2 Comments

oh there was stuff...see the comment. and why is your syntax highlighted not mine?
@tekknolagi try this insertion in first line of the code block: <!-- language: lang-js -->

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.