Throw and Catch in Ruby
Used to exit a block of code upon catching an error. A method throws an error. A catch block catches an error and exits if a method or code within the block throws an error.
def method #code in method throw :someError if errorConditionOccurs #remaining code end catch :someError throw :someError #errors can be thrown directly within a catch block as well method end
If an error is thrown, the method and catch block terminates. If no error is thrown, the rest of the method and catch block executes.
def noNegativeNumbers (number) throw :negativeNumberError if number < 0 puts "Your number is positive!" end catch :negativeNumberError do noNegativeNumbers(5) noNegativeNumbers(-5) #exits catch block here noNegativeNumbers(3) end