kyn*_*kos 12 python exception-handling exception with-statement
这是一个问题的延续使用Python'with'语句捕获异常.
我是新手,我在GNU/linux上使用Python 3.2测试了以下代码.
在上述问题中,提出了类似于此的内容,以便从"with"语句中捕获异常:
try:
with open('foo.txt', 'a'):
#
# some_code
#
except IOError:
print('error')
Run Code Online (Sandbox Code Playgroud)
这让我想知道:如果some_code引发IOError而没有捕获它会发生什么?它显然被外部的"除外"声明所吸引,但这可能不是我真正想要的.
你可以说好,只需用另一个try-except包装some_code,依此类推,但我知道异常可以来自任何地方,并且不可能保护每一段代码.
总而言之,我只是想打印'错误',当且仅当open('foo.txt','a')引发异常时,所以我在这里问为什么以下代码不是标准的建议方式这样做:
try:
f = open('foo.txt', 'a')
except IOError:
print('error')
with f:
#
# some_code
#
#EDIT: 'else' statement is missing, see Pythoni's answer
Run Code Online (Sandbox Code Playgroud)
谢谢!
小智 14
try:
f = open('foo.txt', 'a')
except IOError:
print('error')
else:
with f:
#
# some_code
#
Run Code Online (Sandbox Code Playgroud)