Panic in Ruby

Ruby doesn’t have a direct equivalent to Go’s panic, but we can use exceptions to achieve similar behavior. Here’s how we can translate the concept:

require 'fileutils'

def main
  # We'll use exceptions throughout this site to check for
  # unexpected errors. This is the only program on the
  # site designed to raise an exception.
  raise "a problem"

  # A common use of exceptions is to abort if a method
  # returns an error that we don't know how to
  # (or want to) handle. Here's an example of
  # raising an exception if we get an unexpected error when creating a new file.
  begin
    File.open("/tmp/file", "w")
  rescue StandardError => e
    raise e
  end
end

main

Running this program will cause it to raise an exception, print an error message and backtrace, and exit with a non-zero status.

When the first raise in main is executed, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first raise.

$ ruby panic.rb
panic.rb:7:in `main': a problem (RuntimeError)
    from panic.rb:19:in `<main>'

Note that unlike some languages which use exceptions for handling of many errors, in Ruby it’s common to use both exceptions and error-indicating return values, depending on the situation.

In Ruby, exceptions are used for exceptional circumstances, while regular error handling (like checking return values) is used for expected error conditions. This is somewhat different from Go’s approach, which tends to favor returning error values in most cases.