2006/2/10, Eric Jacoboni <jaco / neottia.net>:
> David Vallner <david / vallner.net> writes:
>
> > Well, File.open in the block version will reraise the exception precisely to
> > let you do that, it's not supposed to silently ignore errors.
>
> Ok, perhaps i'm not clear or perhaps i've missed something...
>
> Suppose i want my script exit with different values depending on the
> error cases:
>
> % ruby -e 'File.open("no.txt") {|f| line = f.gets}'
> -e:1:in `initialize': No such file or directory - no.txt (Errno::ENOENT)
>         from -e:1
> % echo $?
> 1
> % ruby -e 'File.open("yes.txt") {|f| f.puts("bla")}'
> -e:1:in `write': not opened for writing (IOError)
>         from -e:1
>         from -e:1
> [titine]:~/Desktop % echo $?
> 1
>
> As it's clearly not the same error, i don't want the same return
> status. As i don't know how to manage this gracefully with Ruby, i'm
> using a well-know idiom (at least for me...). That said, if there a
> more rubywaying solution, i buy it.

Actually, catching those exceptions and exiting depending on them is
perfectly ok. Although I would question the habit to always handle
exceptions yourself. Often it's not needed and one can end up handling
exceptions too far down the call hierarchy. The nice thing about
Ruby's exceptions is that they are unchecked (borrowing this term from
Java), which basically means that they are not declared. At times this
can make it difficult to figure what exceptions can be thrown from a
method but surprisingly often this is not an issue (at least not for
me, maybe in larger software systems).

Kind regards

robert


PS: A variant you could do for multiple return values to avoid lots of
similar rescue clauses:

RV = Hash.new(1).merge(
  Exception => 1,
  ERRNO::Foo => 2
)

begin
...
rescue Exception => e
  STDERR.puts e
  exit RV[e.class]
end

--
Have a look: http://www.flickr.com/photos/fussel-foto/