Ruby Exceptions — Why “else”?

前端 未结 5 2070
长情又很酷
长情又很酷 2021-01-31 14:11

I\'m trying to understand exceptions in Ruby but I\'m a little confused. The tutorial I\'m using says that if an exception occurs that does not match any of the exceptions iden

5条回答
  •  死守一世寂寞
    2021-01-31 14:38

    The else is for when the block completes without an exception thrown. The ensure is run whether the block completes successfully or not. Example:

    begin
      puts "Hello, world!"
    rescue
      puts "rescue"
    else
      puts "else"
    ensure
      puts "ensure"
    end
    

    This will print Hello, world!, then else, then ensure.

提交回复
热议问题