begin
file = open("/tmp/some_file", "w")
# ... write to the file ...
file.close
end
上面,如果在我们写文件时候发生异常,文件会保留打开.我们也不希望这样冗余出现:
begin
file = open("/tmp/some_file", "w")
# ... write to the file ...
file.close
rescue
file.close
fail # raise an exception
end
这是个笨办法,当增大时,代码将失去控制,我们必须处理每个 和 ,.
为此,我们向"begin...rescue...end"体系中加入了个关键字 ensure. 无论begin块是否成功,ensure代码域都将执行.
begin
file = open("/tmp/some_file", "w")
# ... write to the file ...
rescue
# ... handle the exceptions ...
ensure
file.close # ... and this always happens.
end
可以只用ensure或只用rescue,但当它们在同begin...end域中时, rescue 必须放在 ensure前面.
最新评论