Project

General

Profile

Actions

Bug #13930

closed

Exception is caught in rescue above ensure

Added by msauter (Michael Sauter) over 6 years ago. Updated almost 3 years ago.

Status:
Closed
Target version:
-
ruby -v:
2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]
[ruby-core:82936]

Description

Given the following code:

def foo
  i = 0
  3.times do |n|
    begin
      puts "a"
      i += 1
      next if i > 1
      puts "b"
    rescue => e
      puts "rescue in foo, caught #{e}"
    ensure
      puts "ensure in foo, yield from foo: #{n}"
      yield n
    end
  end
end

begin
  x = 0
  foo do |o|
    puts o
    x += 1
    raise "test" if x > 1
    puts "done yielding"
  end
rescue => e
  puts "rescue outside, caught #{e}"
ensure
  puts "ensure outside"
end

The output is:

a
b
ensure in foo, yield from foo: 0
0
done yielding
a
ensure in foo, yield from foo: 1
1
rescue in foo, caught test
ensure in foo, yield from foo: 1
1
rescue outside, caught test
ensure outside

So the exception raised within the yielded block is caught in the rescue block above the ensure block which yielded. That sounds wrong to me. Or is it intended? The issue seems to be with the usage of next. Also, exception is caught inside AND outside as it seems that the ensure block ends up being called twice ?!

If I change the code to this:

def foo
  i = 0
  3.times do |n|
    begin
      puts "a"
      i += 1
      # next if i > 1
      puts "b"
    rescue => e
      puts "rescue in foo, caught #{e}"
    ensure
      puts "ensure in foo, yield from foo: #{n}"
      yield n
    end
  end
end

begin
  x = 0
  foo do |o|
    puts o
    x += 1
    raise "test" if x > 1
    puts "done yielding"
  end
rescue => e
  puts "rescue outside, caught #{e}"
ensure
  puts "ensure outside"
end

Then the output is:

a
b
ensure in foo, yield from foo: 0
0
done yielding
a
b
ensure in foo, yield from foo: 1
1
rescue outside, caught test
ensure outside

I would have expected this output also when using next as above.


Files

bug13930.disasm (3.62 KB) bug13930.disasm wanabe (_ wanabe), 10/28/2018 08:44 AM
bug13930.patch (492 Bytes) bug13930.patch wanabe (_ wanabe), 10/28/2018 09:00 AM

Related issues 1 (0 open1 closed)

Related to Ruby master - Bug #16618: Ensure called twice when raise in ensureClosedActions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0