I am currently using begin/rescue/end
+ exceptions to implement flow control. So, here is where I am capturing the exceptions and doing different things based on which exception is raised:
collection.each do |object|
begin
process_object(object)
rescue SkippedRowError
# handle skipped row
next
rescue AbortedRowError
# handle aborted row
next
end
end
Because each object from the collection is being processed in a method (process_object
, which calls a bunch of other methods and results in a deeply nested call stack), I can't use next
to stop execution and proceed to the next object in the collection. Hence my use of exceptions.
However, I have read that exceptions should not be used for flow control and that, instead, I should use catch/throw
. So, my question:
Is there a way to accomplish the same thing with catch/throw
?
My conclusion so far: As far as I can tell, catch/throw
is really only useful if you have a single scenario where you want to return early. If you have more than one scenario where you want to return early, then it looks like you have to nest catch
blocks inside of each other. But in that case, you really only get access to a return value; there doesn't seem to be a good way to execute code.