Exceptions Flashcards
1
Q
How to add and handle exceptions?
A
begin raise 'hey' rescue p 'Error was handled' end
2
Q
How to handle and show an error message?
A
begin raise 'hey' rescue => error p error.message end
3
Q
How to add and handle an error with a specific class?
A
begin raise ArgumentError, 'hey' rescue ArgumentError => error p error.message end
4
Q
How to create your own error class?
A
class MyError < StandardError end
begin raise MyError, 'hey' rescue MyError => error p error.message end
5
Q
How to handle several exceptions with different types?
A
begin raise StandardError, 'hey' rescue ArgumentError => error p error.message rescue StandardError => error p error.message end
6
Q
How to rerun code with the exception one more time?
A
# use retry value = true begin raise 'hey' if value p 'works' rescue p 'Try one more time' value = false retry end
7
Q
How to add part of code which should be run every time?
A
ensure
begin raise 'hey' rescue p 'rescue code' ensure p 'ensure code' end
8
Q
What is throw and catch exception? How to use it?
A
# 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