How to add and handle exceptions?
begin raise 'hey' rescue p 'Error was handled' end
How to handle and show an error message?
begin raise 'hey' rescue => error p error.message end
How to add and handle an error with a specific class?
begin raise ArgumentError, 'hey' rescue ArgumentError => error p error.message end
How to create your own error class?
class MyError < StandardError end
begin raise MyError, 'hey' rescue MyError => error p error.message end
How to handle several exceptions with different types?
begin raise StandardError, 'hey' rescue ArgumentError => error p error.message rescue StandardError => error p error.message end
How to rerun code with the exception one more time?
# use retry value = true begin raise 'hey' if value p 'works' rescue p 'Try one more time' value = false retry end
How to add part of code which should be run every time?
ensure
begin raise 'hey' rescue p 'rescue code' ensure p 'ensure code' end
What is throw and catch exception? How to use it?
# tryes to "catch" something that was "throw" # catch and throw work with symbols rather than exceptions.
catch(:finish) do
1000.times do
x = rand(1000)
throw :finish if x == 123
end
puts "Generated 1000 random numbers without generating 123!"
end