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
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.
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.
In Ruby, continue
is spelt next
.
for i in 1..5 begin do_something_that_might_raise_exceptions(i) rescue next # do_something_* again, with the next i end end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With