Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 37 ยท Control Flow and Methods

Exceptions and Error Handling

Handle errors in Crystal with begin, rescue, else, ensure and raise, create custom exception classes, and choose between exceptions, nil returns and the ? method convention.

Things go wrong: files are missing, input is not a number, the network disappears. Crystal reports such problems as exceptions, objects that interrupt the normal flow until something handles them. This lesson shows how to raise, rescue and clean up after exceptions, how to define your own, and how to decide between an exception and a nil result.

Crystal listings are read-only here. Ruby's exception syntax is almost the same, so the stand-ins run the same logic; differences are marked.

Raising an exception

CRYSTAL
def divide(a : Int32, b : Int32) : Int32
  raise ArgumentError.new("b must not be zero") if b == 0
  a // b
end

puts divide(10, 2)    # 5
divide(1, 0)          # Unhandled exception: b must not be zero (ArgumentError)

raise "text" is a shortcut that raises a plain Exception with that message. If nothing handles the exception, the program prints a message with a backtrace and exits with a non-zero status.

Rescuing

Wrap risky code in begin ... rescue ... end:

CRYSTAL
begin
  puts divide(1, 0)
rescue ex : ArgumentError
  puts "Problem: #{ex.message}"
end
puts "program continues"

This prints Problem: b must not be zero, then program continues. After the rescue body runs, execution continues after end.

You can have several rescue clauses, from the most specific to the most general, and each may handle a union of types:

CRYSTAL
begin
  risky
rescue ex : IndexError | KeyError
  puts "lookup failed: #{ex.message}"
rescue ex : ArgumentError
  puts "bad argument: #{ex.message}"
rescue ex
  puts "something else: #{ex.class}"
end

A rescue with no type catches every Exception. Catching everything is sometimes right at the top of a program or request handler, but in the middle of your code it hides bugs. Rescue only what you can handle.

else and ensure

CRYSTAL
begin
  value = "42".to_i
rescue ex : ArgumentError
  puts "not a number"
else
  puts "parsed #{value}"     # runs only when nothing was raised
ensure
  puts "always runs"         # cleanup code
end
  • else runs when the begin body finished without an exception.
  • ensure runs always: after success, after a handled error and even while an unhandled one is propagating. Use it to close files and release resources.

A method body is an implicit begin, so you can write rescue directly inside a def:

CRYSTAL
def read_config(path : String) : String
  File.read(path)
rescue ex : File::NotFoundError
  "{}"            # use an empty config when the file is missing
end

Re-raising and raising new errors

Inside a rescue, raise with no argument raises the same exception again, which is useful after logging. To translate a low-level error into one that fits your domain, raise a new one:

CRYSTAL
begin
  parse_data(text)
rescue ex : ArgumentError
  puts "log: #{ex.message}"
  raise ex                      # pass it on
end

Custom exception classes

Create a class that inherits from Exception (or a more specific subclass):

CRYSTAL
class InsufficientFunds < Exception
  getter needed : Float64

  def initialize(@needed : Float64)
    super("need #{needed} more")
  end
end

def withdraw(balance : Float64, amount : Float64) : Float64
  raise InsufficientFunds.new(amount - balance) if amount > balance
  balance - amount
end

begin
  withdraw(50.0, 80.0)
rescue ex : InsufficientFunds
  puts "Short by #{ex.needed}"    # Short by 30.0
end

Name exceptions after the problem, not the place, and give them the data a handler needs (here, needed). Group related errors under one base class so callers can rescue the whole family.

Ruby Stand-in: custom exceptions in Ruby

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.

In Ruby you rescue StandardError subclasses and write rescue Type => ex. In Crystal you write rescue ex : Type, and custom errors inherit from Exception.

Exceptions, nil or ? methods

Not every failure should be an exception. A guideline that the standard library follows:

Situation Style Example
The caller is expected to handle "not found" Return nil hash["k"]?, "12x".to_i?
Failure means a bug or is exceptional Raise hash["k"] (KeyError), "12x".to_i
Both are useful Offer both to_i and to_i?

Exceptions are not free. Raising one builds a backtrace and unwinds the stack, which is much slower than returning a value. Do not use them for ordinary control flow such as ending a loop.

Ruby Stand-in: nil result versus exception in Ruby

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.

Cleaning up with ensure

Anything that must be released belongs in ensure, or better, in a block-form method that does it for you. File.open with a block closes the file for you even when an exception escapes:

CRYSTAL
File.open("data.txt") do |file|
  puts file.gets
end                        # closed here, whatever happens

Common mistakes

  1. Rescuing Exception everywhere and swallowing real bugs.
  2. Raising strings from library code without a meaningful class.
  3. Using exceptions for expected outcomes in hot loops.
  4. Forgetting that ensure runs even when you return.
  5. Putting too much code in the begin body, so you cannot tell which line failed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which clause always runs, whether or not an exception happened?

    ensure is the cleanup clause. Crystal has no finally keyword.
  2. 2. How do you write a rescue for an ArgumentError and name it ex?

    Crystal uses rescue ex : Type; the => form is Ruby.
  3. 3. What does "12x".to_i? do compared with "12x".to_i?

    The ? variant signals failure with nil; the plain one raises ArgumentError.
  4. 4. Which base class do you normally inherit from to create a custom exception?

    Custom exceptions subclass Exception (or a more specific subclass of it).

Summary

  • raise creates an exception; begin/rescue/else/ensure handles it; a method body is an implicit begin.
  • Use rescue ex : Type, list specific types first and avoid catching everything.
  • ensure runs always and is for cleanup; else runs only on success.
  • Define custom exceptions by inheriting from Exception and carry useful data.
  • Prefer nil returns or ? methods for expected failures and exceptions for exceptional ones.

Next: Classes, Properties and Initialization