2

Where we should use throw-catch instead of other elements of ruby like methods, lambdas/procs, return, raise-rescue etc. in a way that we don't mess up our code (for example we don't need to look for catch/throw in other files/classes)? Or to put it into other words, where I can use throw-catch where I cannot (at least easily) use other forms?

For example, this code (from this answer):

catch (:done) do
  1.upto(INFINITY) do |i|
    1.upto(INFINITY) do |j|
      if j>10
        throw :done, :done
      end
    end
  end
end

you can write as:

 def fun1
   1.upto(INFINITY) do |i|
     1.upto(INFINITY) do |j|
       if j>10
         return :done
       end
     end
   end
 end

In a Ruby I don't like #2 - catch(:wtf) { throw :wtf } post, author showed that the catch is 4 level deeper than the throw. Later, s/he showed that it can be avoided using simple constructs.

So where is unique usage of throw-catch constructs that make our live easier?

Community
  • 1
  • 1
Darek Nędza
  • 1,420
  • 1
  • 12
  • 19
  • 1
    It's for getting out of scopes that are deeper than that. What if you have a function with three inner loops, called from another with loops, called from another, called from main, and you want to pass control back to main? Like a `goto` statement, it's use is very limited, but when needed, it can make code much, *much* cleaner. – Linuxios Jan 16 '14 at 16:22
  • @Linuxios Quote from above post: "Just by looking at this method, you’ll have absolutely no idea who’s gonna be throwing :invalid_query. It could be any method subsequently called while the block is being executed. Only way to know is by doing a global search for throw :invalid_query.". Same applies to your example. – Darek Nędza Jan 17 '14 at 11:23
  • @Cary is talking about `raise/rescue` for all those who got kinda confused.. – cozyconemotel Feb 17 '16 at 06:27
  • In addition to the point made by @Linuxios, rescuing an exception is sometimes the easiest way to check data. Suppose, for example, you are converting string representations of dates to `Date` objects, using `Date#parse`, and encounter '2001-02-0x'. Say you want to log this and continue. Ruby does not have a method that will tell you if a string can be parsed to a date. So you have two choices: write such a method yourself or catch the `ArgumentError` exception that `Date.parse('2001-02-0x')` will raise. The latter is obviously the easier and more reliable. – Cary Swoveland Feb 17 '16 at 06:56
  • @cozyconemotel, thanks for the comment. It appears it wasn't just readers who were confused. – Cary Swoveland Feb 17 '16 at 06:57

0 Answers0