在 python 中捕获 IOError
我编写了一个方法来执行一些操作并捕获错误的文件名。应该发生的情况是,如果路径不存在,则会抛出 IOError。但是,它认为我的异常处理语法不好......为什么?
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
when imported...help?!
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?!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只是在您的
try
块中缺少某些内容,即pass
或任何内容,否则会出现缩进错误。Just missing something in your
try
block, i.e.pass
or anything, otherwise it gives an indentation error.如果您不将某些内容放入
try
块中,您将收到语法错误。您可以输入
pass
只是为了保留空格: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:检查你的缩进。这个无用的
SyntaxError
错误有之前骗过我。:)来自已删除的问题:
Check your indenting. This unhelpful
SyntaxError
error hasfooled me before.:)From the deleted question:
如果您有幸拥有较旧的安装,还有另外一种可能
和
您正在使用“as”语法:
除了 IOError as ioe:
和
解析器被“as”绊倒了。
使用
as
是 Python 2.6 及更高版本中的首选语法。这是 Python 2.5 及更早版本中的语法错误。对于 2.6 之前的版本,请使用:
IOError 除外,ioe:
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: