From: Morton Goldberg Date: 2006-12-12T04:53:26+09:00 Subject: Re: Bug in Ruby or Pickaxe? (was: Re: else inside rescue is useless?) On Dec 11, 2006, at 8:55 AM, Robert Klemme wrote: > def foo(x) > begin > puts "x=#{x}" > > case x > when 0 > puts "returning" > return > when 1 > raise "Some error" > when 2 > raise NameError, "wrong name" > when 3 > break "broken" > else > puts "do something" > end > > puts "unsafe else" > rescue NameError > puts "name error: #{$!}" > else > puts "else" > ensure > puts "leaving!" > end > end > > 5.times do |i| > begin > foo i > rescue Exception => e > puts "Exception: #{e}" > end > end > > With my 1.8.5 I see: > > x=0 > returning > leaving! > x=1 > leaving! > Exception: Some error > x=2 > name error: wrong name > leaving! > x=3 > leaving! > Exception: unexpected break > x=4 > do something > unsafe else > else > leaving! > > What bugs me is that the "else" clause is not executed if it is > left via a "return". Taking the Pickaxe 2nd edition pg. 362 > literally ("If an else clause is present, its body is executed if > no exceptions were raised in code.") it would have to be executed > in that case, too. So, if the interpreter would behave as stated > in the book, there was actually a difference between the code at > the end of the block and the code inside the else clause. I would be horrified if the were executed after a -- is not . The Pickaxe book should be probably say: "If an else clause is present, its body is executed if no exceptions were raised and no exit was made in _code_ ." In fact, I just submitted an erratum to this effect on the Pragmatic Programmer site. > Even in the current situation (where there seems to be no > semantically difference) putting code into the else clause instead > of the end of the block might have an advantage documentation wise. Also from Pickaxe: "Exceptions raised during the execution of the else clause are not captured by rescue clauses in the same block as the else." That seems to be a semantic difference. Regards, Morton