Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Continue a loop after catching an exception

Basically, I want to do something like this (in Python, or similar imperative languages):

for i in xrange(1, 5):     try:         do_something_that_might_raise_exceptions(i)     except:         continue    # continue the loop at i = i + 1 

How do I do this in Ruby? I know there are the redo and retry keywords, but they seem to re-execute the "try" block, instead of continuing the loop:

for i in 1..5     begin         do_something_that_might_raise_exceptions(i)     rescue         retry    # do_something_* again, with same i     end end 
like image 430
Santa Avatar asked Apr 12 '10 19:04

Santa


People also ask

Does raising an error stop execution Ruby?

When you raise an exception in Ruby, the world stops and your program starts to shut down. If nothing stops the process, your program will eventually exit with an error message. Here's an example.

How do you handle exceptions in Ruby?

Ruby also provides a separate class for an exception that is known as an Exception class which contains different types of methods. The code in which an exception is raised, is enclosed between the begin/end block, so you can use a rescue clause to handle this type of exception.


2 Answers

In Ruby, continue is spelt next.

like image 93
Chris Jester-Young Avatar answered Sep 18 '22 21:09

Chris Jester-Young


for i in 1..5     begin         do_something_that_might_raise_exceptions(i)     rescue         next    # do_something_* again, with the next i     end end 
like image 37
Carlo Avatar answered Sep 16 '22 21:09

Carlo