简体   繁体   中英

Regaining control to line after rescue block if begin throws error in ruby

Is there any way to regain control to begin block after performing rescue block like

begin
 .....
 error(not intended but happening intermittently)
 things to execute
rescue
 describe error
end

Is there any way that my code will go to things to execute after describe error

Thanks in advance

There's no goto -like construction in Ruby (fortunately). And it's not possible to use catch-throw because of begin-rescue-end block. So you can try something like this:

def error_handler
  # if this method will raise an error it's possible to catch it here
  # with `rescue` or (and) `ensure`
  p :finalize
end

def one
  1 / rand(0..3)
rescue
  error_handler
end

def two
  1 / rand(0..3)
rescue
  error_handler
end

def three
  1 / rand(0..3)
rescue
  error_handler
end

begin
  one
  two
  three
  1 / rand(0..3)
rescue => error
  error_handler
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM