在Python中捕获IOError异常

14

我编写了一个方法来执行某些操作并捕获错误文件名。如果路径不存在,则应抛出IOError异常。但是,它认为我的异常处理语法不正确...为什么?

def whatever():
    try:
        #执行操作
        #和更多操作
    except IOError:
        #将做这个
        pass
whatever()

但在调用whatever()之前,就已经输出了以下内容:

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

在导入时...有帮助吗?!

4个回答

10

请检查您的缩进。这个不太有用的SyntaxError错误以前曾经欺骗过我。 :)

从被删除的问题中:

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

@tekknalogi:你怎么知道它不会?你收到了什么错误信息? - Falmarri
很遗憾,该链接已经不存在了。能否解释一下问题出在哪里? - Exa

5
如果您的Python安装版本比较老,还使用“as”语法,那么就有可能出现另外一种情况。解析器会因为“as”而出错。在Python 2.6及以上版本中,使用“as”是首选的语法。但在Python 2.5及更早版本中,这是语法错误。对于这种情况,请使用以下代码:except IOError, ioe:

嗯,我来这里是为了寻找这个。谢谢。 - skjoshi

2

在您的try代码块中,缺少某些内容,例如pass或其他任何内容,否则会导致缩进错误。


1
如果你不在try块中放置任何内容,就会得到语法错误。 你可以放置pass来占位:
try:
    # do stuff
    # and more stuff
    pass
except IOError:
    # do this
    pass

1
哦,有些东西...看看注释。为什么你的语法高亮而我的不是? - tekknolagi
@tekknolagi 尝试在代码块的第一行插入以下内容:<!-- language: lang-js --> - John Greene

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接