I am currently reading Avdi Grimm's Confident Ruby and it has been great learning curve. I also discoverered Ruby Book Club podcast by Nadia and Saron and it has been a great journey to read a chapter by chapter and listening ladies discuss about the book.
Anyway, I found this chapter - 5.7 Early Termination with Throw, very interesting so would like to introduce to ya all.
First question I need to ask before using catch and throw is that when to use. This is most likely useful when we want to stop the recursive process without throwing an error.
Use throw to signal the early termination, and catch to handle it.
Catch and Throw could be used more complex cases but in nutshell, it allows the program stops when it found essential value. This pattern also limit outselves using raising Errors to stop the program e.g. raise DoneError in the middle of the method or using begine, rescue end (BRE) block
Avdi Grimm also explains why we should not use BRE block - he says "BRE is the pink lawn Xamingo of Ruby code: it is a distraction and an eyesore wherever it turns up" because it breaks flows of the method.
His suggestion for the error handling case is using top-level rescue clause.
This will clearly shows what foo function supposed to be. If things goes south, it can be handled by rescue. Let's look at another trick called 'Bouncer method'. A Bouncer Method is a method whose sole job is to raise an exception if it detects an error condition.
Enter the bouncer method.
We can even go further. We can yield the result of the main method and then raise error if the result is failed.
Conclusion: Use top-level rescue to rescue failure. Think of flow of the method. "When given an intention-revealing name, it can clearly and concisely reveal to the reader exactly what potential failure is being detected. And it can DRY up identical error-checking code in other parts of the program."