# Did You Know that You Can Catch and Throw Stuff in Ruby?

*Published on May 09, 2023*

---


> 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.  
>   
> \- Pragmatic Programmers, 2001

If like me, you're coming to Ruby from traditional programming languages, the `throw` and `catch` methods might surprise you.

No, they're not used for throwing and handling errors (although you can use them for that). Instead, they manage the control flow of your Ruby code, by allowing you&nbsp;**to terminate execution early and escape deeply nested control flows,**&nbsp;without having to use&nbsp;`break`,&nbsp;`return`, or&nbsp;`raise-rescue`.

In this post, we'll cover the basics of using&nbsp;`throw`&nbsp;and&nbsp;`catch`&nbsp;in Ruby, including how these methods work and when should you use them. We'll also see a few real-world use cases, including how the Warden gem uses&nbsp;`throw-catch`&nbsp;for authentication and how Sinatra uses them to immediately halt a request.

## What We'll Learn:

- Introduction to&nbsp;`throw`&nbsp;and&nbsp;`catch`
- Why and when should you use them?
- In the wild: How warden uses&nbsp;`throw`&nbsp;and&nbsp;`catch`
- Performance comparison with&nbsp;`raise`&nbsp;and&nbsp;`rescue`
- How to test it?
- Conclusion

Sounds fun? Let's begin.

## Introduction to Throw and Catch

In this section, we'll inspect the API of both of these methods in detail.

**`Kernel#throw(tag, obj)`**

The&nbsp;[`throw`](https://ruby-doc.org/3.2.0/Kernel.html#method-i-throw)&nbsp;method is defined in the&nbsp;`Kernel`&nbsp;module, hence you can call it anywhere in your Ruby code. You can pass it a symbol (`tag`), and optional data.

`throw`&nbsp;transfers control to the end of the active&nbsp;`catch`&nbsp;block waiting for the&nbsp;`tag`. If there is no&nbsp;`catch`&nbsp;block for the&nbsp;_`tag`__,_&nbsp;Ruby will raise an&nbsp;`UncaughtThrowError`.

The optional second parameter provides a return value for the&nbsp;`catch`&nbsp;block, which otherwise defaults to&nbsp;`nil`.

```ruby
msg = catch(:tag) do
  # do something
  
  throw :tag, 'no match found'
  
  puts 'this is not executed'
end

puts msg  # no match found
```

It's important to note that`throw`&nbsp;works just like&nbsp;`return`. Any code you write after it&nbsp;**will not be executed**. In the above example, the first&nbsp;`puts`&nbsp;call won't run.

**`Kernel#catch`**

The&nbsp;[`catch`](https://ruby-doc.org/3.2.0/Kernel.html#method-i-catch)&nbsp;method is also defined in the&nbsp;`Kernel`&nbsp;module, and it accepts a symbol (`tag`) and a block. First, it executes the block, which can either call the&nbsp;`throw`&nbsp;method or not.

- If the &nbsp;`throw`&nbsp;method is not called anywhere in the block, the block executes normally. The&nbsp;`catch`&nbsp;returns the value of the last expression evaluated in the block.

```ruby
msg = catch(:err) do
  # do something
  'success'
end

puts msg  # success
```

- If the block calls the&nbsp;`throw`&nbsp;method with the matching&nbsp;`tag`&nbsp;(the symbol passed to&nbsp;`catch`), the block stops executing and returns whatever arguments you passed to&nbsp;`throw`&nbsp;method (see&nbsp;`obj`&nbsp;in the&nbsp;`throw`&nbsp;method above). It returns&nbsp;`nil`&nbsp;if no second argument was given to&nbsp;`throw`&nbsp;method.

```ruby
msg = catch(:err) do
  throw :err, 'something went wrong'
  puts 'this is not executed'
end

puts msg  # something went wrong
```

When you call the&nbsp;`throw`&nbsp;method, the Ruby interpreter walks up the stack until it finds a corresponding catch.

**Throwing something always requires that someone should be there to catch it.**&nbsp;If you try to&nbsp;`throw`&nbsp;something without having a matching&nbsp;`catch`, Ruby will raise an&nbsp;`UncaughtThrowError`.

```ruby
# uncaught throw :err (UncaughtThrowError)
throw :err, 'something went wrong'

# uncaught throw :error (UncaughtThrowError)
catch(:err) do
  throw :error, 'something went wrong'
end
```

Now you might be wondering why and when we might need to use&nbsp;`catch`&nbsp;and&nbsp;`throw`. So let's take a look at a few use cases.

## Why and When Should You Throw and Catch?

Typically, you'll use&nbsp;`throw`&nbsp;and&nbsp;`catch`&nbsp;to escape from multiple levels of loops and conditionals, just like a good old&nbsp;`GOTO`&nbsp;statement.

I know you can use the&nbsp;`break`&nbsp;statement to exit loops, but &nbsp;`break`&nbsp;will only halt the computation on the innermost loop in which it's called. If you have multiple nested loops, the outer loop still continues, as the following example shows.

```ruby
3.times do |i|
  3.times do |j|
    puts i
    break
    print j
  end
  
  puts 'still here'
end

# Output: 

# 0
# still here
# 1
# still here
# 2
# still here
```

In contrast,&nbsp;`throw`&nbsp;provides an elegant way to jump out of multiple loops.

```ruby
catch(:err) do
  3.times do |i|
    3.times do |j|
      puts i
      throw :err
      print j
    end
    
    puts 'still here'
  end
end

# Output:

# 0
```

Another excellent use case for&nbsp;`throw-catch`&nbsp;is when you have some computation taking place in the deep bowels of your codebase and need to eject immediately, as soon as some condition (not an error!) is met.

In fact, this is exactly how Warden uses it. The next section shows how.

## In the Wild: How Warden Uses Throw-Catch

[Warden](https://github.com/wardencommunity/warden)&nbsp;is a Rack-based middleware, designed to provide a mechanism for authentication in Ruby web applications. It is a common mechanism that fits into the Rack middleware system to offer powerful options for authentication.

You may not have heard about Warden, but you must have used or heard of&nbsp;[Devise](https://github.com/heartcombo/devise), which provides a complete authentication solution for Rails applications.&nbsp;**Devise uses Warden under the hood.**

To learn more about Rack and the concept of middleware, check out the following articles, from yours truly:

- [The Definitive Guide to Rack for Rails Developers](/definitive-guide-to-rack)
- [Middleware in Rails: What It Is, How It Works, and Examples](/rails-middleware-what-why-and-how)

Okay, back to Warden. To reiterate, Warden provides a mechanism for authentication in Rack-based web applications.

Warden enables all the middleware components that are next in the pipeline to share a common authentication solution. Each middleware that comes after the warden middleware can layer whatever API they want on top of it, and everything still works.

In fact, that's how Devise uses Warden.

Let's inspect the Warden middleware's&nbsp;`call`&nbsp;method. I'll skip the code that comes before and after the&nbsp;`catch`&nbsp;method, as it's not relevant to this discussion.

```ruby
# lib/warden/manager.rb

def call(env)
  # set up warden
  
  result = catch(:warden) do
    @app.call(env)
  end
  
  # process the result
end
```

As you can see, Warden calls the&nbsp;`catch`&nbsp;method, passing the symbol&nbsp;`:warden`&nbsp;and a block that simply forwards the request to the next middleware&nbsp;`@app.call(env)`.

When a user tries to log in, Warden calls the&nbsp;`authenticate!`&nbsp;method which performs the authentication.

```ruby
# lib/warden/proxy.rb

def authenticate!(*args)
  user, opts = _perform_authentication(*args)
  throw(:warden, opts) unless user
  user
end
```

If the user is missing, that means the authentication failed, and Warden throws the&nbsp;`:warden`&nbsp;symbol, which is caught by the&nbsp;`catch`&nbsp;method we saw earlier. Then it processes the result and the additional arguments passed in the&nbsp;`throw`&nbsp;method.

**Here's another example:**&nbsp;[Sinatra](https://sinatrarb.com/intro)&nbsp;uses&nbsp;`throw`&nbsp;and&nbsp;`catch`&nbsp;to implement the&nbsp;[`halt`](https://github.com/sinatra/sinatra/blob/main/lib/sinatra/base.rb#L975)&nbsp;method, which lets you immediately terminate a request at any time.

```ruby
# Run the block with 'throw :halt' support and apply result to the response.
def invoke(&block)
  res = catch(:halt, &block)
  
  # remaining code
end

# Exit the current block, halts any further processing
# of the request, and returns the specified response.
def halt(*response)
  response = response.first if response.length == 1
  throw :halt, response
end
```

Pretty interesting, don't you think?

## Performance Comparison with Raise and Rescue

`throw-catch`&nbsp;is significantly faster than&nbsp;`raise-rescue`, as shown by Josh on&nbsp;[StackOverflow](https://stackoverflow.com/a/13484425/5192528).

```ruby
require 'benchmark'

Benchmark.bmbm do |x|
  x.report('Break') do
    1_000_000.times do
      break
    end
  end

  x.report('Catch/Throw') do
    1_000_000.times do
      catch(:benchmarking) do
        throw(:benchmarking)
      end
    end
  end

  x.report('Raise/Rescue') do
    1_000_000.times do
      begin
        raise StandardError
      rescue
        # do nothing
      end
    end
  end
end
```

**Output**

```bash
                   user     system      total        real
Break          0.000008   0.000001   0.000009 (  0.000005)
Catch/Throw    0.307164   0.001274   0.308438 (  0.310073)
Raise/Rescue   1.013735   0.008861   1.022596 (  1.027078)
```

One of the reasons for this dramatic difference is that&nbsp;`raise-rescue`&nbsp;creates&nbsp;`backtrace`, which is not needed for&nbsp;`catch-throw`. ([source](https://stackoverflow.com/a/17312466/5192528))

## How to Test?

To test if a block throws a symbol, use the&nbsp;[`assert_throws`](https://www.rubydoc.info/gems/minitest/4.3.3/MiniTest%2FAssertions:assert_throws)&nbsp;method in Minitest.

```ruby
def check
  throw :expired, 'status is expired'
end
  
test 'throws the status if user is expired' do
  assert_throws(:expired) { User.new.check }
end
```

If you're using RSpec, use the&nbsp;`throw_symbol`&nbsp;expectation.

```ruby
expect { ... }.to throw_symbol
expect { ... }.to throw_symbol(:symbol)
expect { ... }.to throw_symbol(:symbol, 'value')
```

Although testing this is well and good, don't forget to test the actual side-effect you want to have after the&nbsp;`symbol`&nbsp;is caught.

## Conclusion

> `throw-catch`&nbsp;offers a way to escape from deeply nested, multiple layers of control flow without having to resort to&nbsp;`raise-rescue`.

To summarize,&nbsp;`throw-catch`&nbsp;is used for jumping out of control statements, when no further work is required. In contrast,&nbsp;`raise-rescue`&nbsp;is used for error handling. It's not that one is better than the other. You have to use them according to the needs of your program.

**When should you use**&nbsp;**`throw-catch`****?**&nbsp;To be honest, not very often, unless you really know you need it, just like the Warden gem.

![dog_frisbee.jpeg](https://writesoftwarewell.com/media/3wj8yw2senpv7gseo2pun16a4zey.jpeg "Dog with a frisbee")

