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
begin … rescue … endcatches errors raised inside it.rescue SomeError => ecatches that class (and its subclasses) and gives you the error object.raise SomeError, "message"raises one. Plainraise "message"raises aRuntimeError.
The full shape
| 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:
Always limit retries, or a permanent failure turns into an infinite loop.
The exception hierarchy
- Rescue
StandardError(what a barerescuecatches) for "anything that went wrong". - Never rescue
Exceptionitself: it includesInterrupt(Ctrl + C) andSystemExit, so your program would refuse to stop.
Your own error classes
Define errors for your domain so callers can rescue exactly what they expect:
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:
Reading and writing files
Each editor here starts with an empty folder, so these examples create their own files.
| 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
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:
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
- Write
safe_divide(a, b)that returnsnilfor division by zero instead of raising. - Define
InvalidEmail < StandardErrorand raise it fromvalidate_emailfor strings without@. - Write a list of tasks to
todo.txt, one per line, then read it back and print them numbered. - Read a CSV of names and ages (create it first) and write the adults to
adults.json.
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"?