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.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading