catching an IOError in python

tekknolagi picture tekknolagi · Feb 2, 2011 · Viewed 33.6k times · Source

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?!

Answer

Brian M. Hunt picture Brian M. Hunt · Feb 2, 2011

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