在Python中捕获IOError

14 投票
4 回答
41843 浏览
提问于 2025-04-16 11:03

我写了一个方法,用来处理一些事情,并且能捕捉到不好的文件名。正常情况下,如果路径不存在,它应该会抛出一个IO错误。但是,它却认为我的异常处理写得有问题……这是为什么呢?

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

但是在它调用whatever()之前,它就打印出了以下内容:

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

当被导入时……求助?!

4 个回答

2

在你的 try 代码块里缺少了一些东西,比如 pass 或者其他的内容,不然会出现缩进错误。

5

还有一种可能性,如果你有一个比较旧的安装版本的话。

并且

你在使用 'as' 这种写法:

     except IOError as ioe:

并且

解析器在处理 'as' 时可能会出问题。

在 Python 2.6 及更高版本中,使用 as 是推荐的写法。

但是在 Python 2.5 及更早版本中,这种写法会出错。对于 2.6 之前的版本,你应该使用这个:

     except IOError, ioe:

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

撰写回答