在python中捕获IOError
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4869476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
catching an IOError in python
提问by tekknolagi
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??
我写了一个方法来做一些事情并捕获错误的文件名。应该发生的情况是,如果路径不存在,则会引发 IOError。然而,它认为我的异常处理是错误的语法......为什么?
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:
但在它开始调用之前whatever(),它会打印以下内容:
Traceback (most recent call last):
File "", line 1, in
File "getquizzed.py", line 55
except IOError:
^
SyntaxError: invalid syntax
when imported...help?!
导入时...帮助?!
采纳答案by Brian M. Hunt
Check your indenting. This unhelpful SyntaxErrorerror has fooled me before.:)
检查你的缩进。这个无益的SyntaxError错误之前曾愚弄过我。:)
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
回答by unutbu
You will get a syntax error if you don't put something in side the tryblock.
You can put passjust to hold the space:
如果你没有在try块旁边放东西,你会得到一个语法错误。您可以pass只放置空间:
try:
# do stuff
# and more stuff
pass
except IOError:
# do this
pass
回答by Benjamin
Just missing something in your tryblock, i.e. passor anything, otherwise it gives an indentation error.
只是在你的try块中遗漏了一些东西,即pass或任何东西,否则它会给出一个缩进错误。
回答by Der Schley
there's 1 more possible if you're privileged to have an older installation
如果您有权拥有较旧的安装,还有 1 个可能
and
和
you're using the 'as' syntax:
您正在使用“as”语法:
except IOError as ioe:
except IOError as ioe:
and
和
the parser's getting tripped up on 'as'.
解析器被“as”绊倒了。
Using asis the preferred syntax in Python 2.6 and better.
Usingas是 Python 2.6 及更高版本中的首选语法。
It's a syntax error in Python 2.5 and older. For pre-2.6, use this:
这是 Python 2.5 及更早版本中的语法错误。对于 2.6 之前的版本,请使用:
except IOError, ioe:
except IOError, ioe:

