From: Robert Klemme Date: 2003-06-02T17:23:42+09:00 Subject: Re: Return from ensure "Gennady" schrieb im Newsbeitrag news:001101c32624$5aef3490$c20ca8c0@gfb... > Hi, Rubyists > > Actually, I saw a remark on ruby-talk once that "return" is dagerous, > however I could not imagine it is that dangerous. Today I spent 2 hours > debugging the code that looked perfectly normal otherwise. I was able reduce > the code to the following fragment: > > def test > begin > raise "ERROR" > ensure > return "some value" > end > end > > test > puts "Nothing happened" > > > Yes, it prints out "Nothing happened", and if you comment out "return" you > will see the exception. I just wanted to provide a return value for the > function here, so I naturally used "return" statement. I know that in Ruby > you can return something without explicit "return" and I usually do this > every time. However, at that unfortunate moment my instinct injected > "return" -- and, here we go, 2 hours of fun. > > Any comments? "ensure" is inappropriate for catching exceptions and returning something else. You must use "rescue" for this. The purpose of "ensure" is to have a piece of code that is invoked regardless of how the block is exited. This code however should only do cleanup and not modification of the exit procedure - as you have experienced. You'll find this very nicely documented in the pickaxe chapter "Exceptions, Catch, and Throw". Regards robert