Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 134 ยท Control Flow

catch and throw

Learn Ruby's catch and throw for non-local exits from nested loops and methods, how they differ from exceptions and break, UncaughtThrowError, and when to avoid them.

break leaves one loop. return leaves one method. But what if you are three loops deep, inside a block, inside a helper method, and you have just found the answer? Ruby offers two tools that jump out of arbitrarily deep code in one step: exceptions (see Exceptions) and the lesser known pair catch and throw.

catch marks a spot in your code with a label. throw jumps to that spot from anywhere inside, optionally carrying a value. Nothing is "wrong" in this situation, so no error is involved. This lesson shows how the pair works, compares it with break, return and raise, and explains why most Ruby programmers use it rarely.

The basic idea

Ruby catch and throw

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

catch(:found) do ... end runs its block. If the block finishes normally, catch returns the value of the last expression. If throw :found, value runs anywhere inside, even in a nested method, the block stops immediately, and catch returns value. Here the loop stops at 3, "nothing found" is never printed and the result is 300. If you throw without a value, catch returns nil.

The label is usually a symbol, but any object works, and identity decides the match. A fresh Object.new makes a label that cannot collide with anyone else's.

Escaping nested loops

The classic use: find the first match in a grid or in several nested loops, where break would leave only the innermost one.

Ruby Leaving nested loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You could write the same thing with a method and return, and often that is the better solution, as the next example shows.

Ruby The same search with a method and return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A return from inside a block leaves the whole method, no matter how many blocks are nested. A named method also documents what you are doing. Prefer it whenever the search can live in its own method. Reach for catch when the exit crosses method boundaries, or when giving the code its own method would be awkward.

Throwing from a nested method call

The real strength of throw is that it works across method calls. The thrower does not need to know about the catch, only the label.

Ruby Throwing from a helper method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The traversal is recursive, and the throw unwinds all the recursion levels at once. Nodes a3 and b are never visited. Without throw, you would have to return a flag from every level and check it after every recursive call.

What happens without a matching catch

A throw with no matching catch is a programming error, and Ruby reports it as an exception.

Ruby An uncaught throw (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The program prints before, then fails with main.rb:2:in 'Kernel#throw': uncaught throw :stop (UncaughtThrowError). UncaughtThrowError is a subclass of ArgumentError, so you can rescue it like any other error. It carries the label in tag and the value in value.

Ruby Rescuing an uncaught throw

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Labels are matched with equal?, so catch("a") does not match throw "a" (two different string objects). Use symbols or a shared constant.

catch with no label, and ensure

If you call catch without arguments, Ruby creates a unique label and passes it to the block. Nobody else can throw to it by accident, which is the safest form for libraries.

Ruby An anonymous label and ensure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The block parameter tag is the generated label. Cleanup in ensure blocks still runs as the throw unwinds, just as with exceptions, so resources are released correctly.

catch/throw versus the alternatives

Tool Leaves Carries a value Typical use
break the innermost loop or block yes (break value) stop one loop
next the current block iteration yes skip an item
return the whole method yes return from a method
throw up to the matching catch yes expected early exit from deep code
raise up to a matching rescue the exception object errors

throw is not an error mechanism. Use raise for failures, because exceptions have classes, messages and backtraces, and rescue blocks are the expected place to handle them. Use throw for a successful early exit, where finding the answer simply means "stop looking".

Ruby's catch/throw has nothing to do with try/catch in JavaScript, Java or C++. In those languages catch handles errors; in Ruby you use rescue for that.

Performance and style

A throw is cheap: it does not build an exception object or capture a backtrace, so it costs less than raising and rescuing. Even so, speed is not the reason to choose it. Its downside is readability: the reader of throw :found must search the code for the matching catch. Because of this, many Ruby style guides discourage it, and you will see it mainly in a few places:

  • libraries that implement their own search or traversal (Sinatra's halt is built on it);
  • parsers and template engines that need to abort deep recursion;
  • code where a helper method is not an option.

Before using it, ask: can I extract a method and use return? Can I use find, detect or any? (see Iterators) instead of a manual loop? Often the answer is yes, and the code is simpler:

Ruby Often an Enumerable method is enough

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does catch(:done) { throw :done, 7; 99 } return?

    throw jumps straight to the matching catch and makes it return the thrown value, so the 99 is never evaluated.
  2. 2. What happens when you call throw :x and no catch(:x) is active?

    An unmatched throw is reported as UncaughtThrowError, a subclass of ArgumentError.
  3. 3. How do catch/throw differ from raise/rescue in intent?

    Use raise for failures that need a class, message and backtrace, and throw for non-error control flow that crosses several levels.
  4. 4. In a method with nested each blocks, which statement leaves the whole method with a value?

    return inside a block returns from the enclosing method. break only leaves the loop or block it is in.
  5. 5. Why does catch("a") { throw "a" } fail with two string literals?

    Ruby compares tags with equal?. Two separate string objects with the same text are not the same object; symbols are.

Summary

  • catch(label) { ... } returns either the block's last value or the value passed to throw label, value.
  • throw can come from any depth, including other methods, and unwinds the stack, running ensure blocks.
  • Without a matching catch, throw raises UncaughtThrowError; labels match by identity, so use symbols.
  • Use it for expected early exits from deeply nested code; use raise for errors.
  • Prefer return from a helper method or find/any? when they are enough, because throw is harder to follow.

Next: Immutability and freeze