From: Gennady Bystritsky Date: 2006-02-11T01:10:07+09:00 Subject: Re: Yet another question on exceptions File.open is not that stupid ;-). It uses "ensure" internally to close a file in the case of exception. Using block with open guarantees that the file will not remain open no matter what. Gennady. > -----Original Message----- > From: Eric Jacoboni [mailto:jaco@neottia.net] > Sent: Friday, February 10, 2006 8:03 > To: ruby-talk ML > Subject: Yet another question on exceptions > > Hi, > > If i use File::open 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? > -- > Eric Jacoboni, ne il y a 1442972561 secondes > >