Throw vs. Raise

  • catch/throw are control flow, allowing you to quickly exit blocks back to a point where a catch is defined for a specific symbol
  • raise, fail, rescue, & ensure handle errors, a.k.a. exceptions, the actual Exception object.

From: Grimm, Avdi. "Throw, Catch, Raise, Rescue… I’m so Confused!"

Unlike in other languages, Ruby’s throw and catch are not used for exceptions. Instead, they provide a way to terminate execution early when no further work is needed. (Grimm, 2011)

  • Terminating a single level of control flow, like a while loop, can be done with a simple return. Terminating many levels of control flow, like a nested loop, can be done with throw.

From: Thomas, Dave, and Andrew Hunt. "Programming Ruby."

While the exception mechanism of raise and rescue is great for abandoning execution when things go wrong, it's sometimes nice to be able to jump out of some deeply nested construct during normal processing. This is where catch and throw come in handy. (Thomas and Hunt, 2001)


References

results matching ""

    No results matching ""