Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

RB
Ruby
0/12 completed
Beginner
Hello RubyVariables and typesConditions and loopsMethods
Intermediate
Arrays and hashesBlocks, procs and iteratorsClasses and objectsModules and mixins
Advanced
Exceptions and filesMetaprogramming
Pro
Gems, Bundler and testingRuby on Rails basics
Tracks / Ruby / Advanced

Exceptions and files

Programs meet bad input, missing files and network failures. Ruby handles these with exceptions: an error object is raised, and code further up can rescue it. This lesson covers raising and rescuing, defining your own errors, and reading and writing files, which is where most real-world errors come from.

Rescuing errors

Ruby · editable
  • begin … rescue … end catches errors raised inside it.
  • rescue SomeError => e catches that class (and its subclasses) and gives you the error object.
  • raise SomeError, "message" raises one. Plain raise "message" raises a RuntimeError.

The full shape

Ruby · editable
Part Runs
rescue When a matching error is raised
else Only when no error was raised
ensure Always, error or not: close files, release locks

Inside a method (or a do … end block), you can write rescue / ensure directly, without begin, as above.

retry

retry runs the begin block again, which is useful for flaky network calls:

Ruby · editable

Always limit retries, or a permanent failure turns into an infinite loop.

The exception hierarchy

Ruby · editable
  • Rescue StandardError (what a bare rescue catches) for "anything that went wrong".
  • Never rescue Exception itself: it includes Interrupt (Ctrl + C) and SystemExit, so your program would refuse to stop.

Your own error classes

Define errors for your domain so callers can rescue exactly what they expect:

Ruby · editable

A base class (Shop::Error) lets callers rescue every error from your code at once.

Uncaught errors

If nothing rescues an error, the program stops and prints the error with a backtrace, the chain of method calls that led there. Read it from the top:

Ruby · editable

Reading and writing files

Each editor here starts with an empty folder, so these examples create their own files.

Ruby · editable
Mode Opens for
"r" Reading (default)
"w" Writing: erases the file first
"a" Appending
"r+" Reading and writing

File.open with a block closes the file automatically when the block ends, even if an error is raised. Without a block you must call close yourself, so prefer the block form.

Missing files

Ruby · editable

Errors from the operating system are classes inside Errno: ENOENT (no such file), EACCES (permission denied) and so on.

CSV and JSON

Ruby's standard library reads and writes JSON. For CSV, the csv library became a separate gem in Ruby 3.4 (gem install csv, or add it to your Gemfile). For simple files without quoted commas, splitting lines works too:

Ruby · editable

With the csv gem installed, CSV.read("sales.csv", headers: true, converters: :numeric) does the same and also handles quoted fields that contain commas.

Practice

  1. Write safe_divide(a, b) that returns nil for division by zero instead of raising.
  2. Define InvalidEmail < StandardError and raise it from validate_email for strings without @.
  3. Write a list of tasks to todo.txt, one per line, then read it back and print them numbered.
  4. Read a CSV of names and ages (create it first) and write the adults to adults.json.
✎ Check your understanding

1.When does an ensure block run?

2.Why shouldn't you rescue Exception?

3.What does File.open("log.txt", "w") do to an existing log.txt?

4.Which error class means "no such file or directory"?

← Modules and mixins