Codectionary / Developer documentation / Ruby

Ruby Exceptions

Ruby signals exceptional failures by raising exceptions. rescue handles a matching exception, while ensure runs whether the operation succeeded or failed.

Syntax

begin
  risky_work
rescue StandardError => error
  puts error.message
end

Examples

Handling a conversion error

A small, runnable example of this syntax.

begin
  age = Integer("not a number")
rescue ArgumentError => error
  puts "Please enter a number: #{error.message}"
end

Best practices

  • Rescue specific exception classes when possible so unexpected failures are not silently hidden.
  • Keep examples small while learning, then combine the idea with a real project.

At a glance

Purpose
Expressive scripting and applications
File extension
.rb
Runs in
Ruby interpreter
Usually used with
Ruby standard library and gems

Specifications & further reading

Related Ruby documentation