Ruby
Error Handling
Raise and rescue typed exceptions with ensure and retry.
By EZ4Code Team
errorexceptionrescue
Code
class ValidationError < StandardError
attr_reader :field
def initialize(field, msg)
@field = field
super(msg)
end
end
def validate_age(age)
raise ValidationError.new(:age, "must be >= 0") if age < 0
raise ValidationError.new(:age, "must be <= 130") if age > 130
"ok"
end
# begin/rescue/ensure
def process(age)
begin
result = validate_age(age)
puts "result: #{result}"
rescue ValidationError => e
puts "Validation failed on #{e.field}: #{e.message}"
rescue => e
puts "Unexpected: #{e.class}"
ensure
puts "cleanup"
end
end
process(25)
process(-1)
process(200)
# Retry on transient failure
attempts = 0
begin
attempts += 1
raise "boom" if attempts < 3
puts "succeeded on attempt #{attempts}"
rescue => e
puts "attempt #{attempts} failed: #{e.message}"
retry if attempts < 3
end
# else and ensure
def divide(a, b)
result = a / b
puts "computed"
result
rescue ZeroDivisionError
:undefined
ensure
puts "always runs"
end
puts divide(10, 2)
puts divide(1, 0)Explanation
Exceptions inherit from StandardError and are raised with raise, then caught by class with rescue. Custom exception classes carry extra fields for richer error context. ensure runs whether or not an exception was raised, and retry re-executes the begin block, useful for transient failures.
More Ruby Snippets
Blocks, Procs, Lambdas
Use blocks with yield, Procs, lambdas, and the & operator.
Classes and Modules
Define classes with inheritance, mix in modules, and add class methods.
Iterators
Use each, map, select, reduce, group_by, and lazy enumerators.
Strings
Interpolate, trim, split, replace, and pattern-match strings.
Hashes
Build, default, transform, merge, and group with Hash.
Metaprogramming
Define methods dynamically, intercept with method_missing, and build DSLs.