E
Eric Jacoboni
Hi,
If i use File:pen to open/create a file objet, and if i use a block
with it, the file will be automatically close when the block ends:
Now, considering this buggy snippet:
begin
File.open("my_file") do |fic|
fic.puts("bla")
end
rescue Exception => e
STDERR.puts(e)
exit(1)
end
Here, the "not opened for writing" exception will be raised, the block
end will never be reached and the file will remain opened, isn't it ?
To circumvent this, i have to make fic a global variable and put the
appropriate code in a ensure clause (or open a begin/ensure in the
File.open block to close the file... too bad)
So, my question is: what's the benefit of this idiom versus this one:
begin
fd = File.new("my_file")
...
rescue Exception => e
STDERR.puts(e)
exit(1)
ensure
fd.close if fd and not fd.closed?
end
Is there something i've missed?
If i use File:pen to open/create a file objet, and if i use a block
with it, the file will be automatically close when the block ends:
Now, considering this buggy snippet:
begin
File.open("my_file") do |fic|
fic.puts("bla")
end
rescue Exception => e
STDERR.puts(e)
exit(1)
end
Here, the "not opened for writing" exception will be raised, the block
end will never be reached and the file will remain opened, isn't it ?
To circumvent this, i have to make fic a global variable and put the
appropriate code in a ensure clause (or open a begin/ensure in the
File.open block to close the file... too bad)
So, my question is: what's the benefit of this idiom versus this one:
begin
fd = File.new("my_file")
...
rescue Exception => e
STDERR.puts(e)
exit(1)
ensure
fd.close if fd and not fd.closed?
end
Is there something i've missed?