Question

  1. What is the difference between using ensure:

    begin
      foo_process
    rescue
      bar_process
    ensure
      baz_process
    end
    

    and putting the process after the begin ... rescue ... end block?

    begin
      foo_process
    rescue
      bar_process
    end
    baz_process
    
  2. What is the difference between using else:

    begin
      foo_process
    rescue
      bar_process
    else
      baz_process
    end
    

    and continuing that process before rescue (supposing that baz_process does not raise an error)?

    begin
      foo_process
      baz_process
    rescue
      bar_process
    end
    
Was it helpful?

Solution

1.

Using ensure, baz_process is alway executed even though foo_process throw exception, return from method.

For example,

def foo_process
  puts 'foo_process'
  return 111
end

def f1
  begin
    return foo_process
  rescue 
    puts 'bar_process'
  ensure 
    puts 'baz_process'
  end
end

def f2
  begin
    return foo_process
  rescue 
    puts 'bar_process'
  end
  puts 'baz_process'
end

>> f1
foo_process
baz_process
=> 111
>> f2
foo_process
=> 111

OTHER TIPS

For question 1, using ensure, baz_process will always be run, even if an exception is not caught by the rescue block (i.e. in your example code, even if the exception is not a StandardError). It will also be run if bar_process raises an exception. Neither of these things are true for code placed after the begin...rescue...ensure block.

For question 2, the difference is that exceptions thrown by code in the else block are not rescued. This is more relevant when there is also an ensure block, as the code will run before it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top