Control Flow

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.


Syntax
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

Notes

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.


Example
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

See Also
Documentation

Module: Kernel - Ruby Docs

Add to Slack

< Ternary Operator   |   Functions >

© 2019 SyntaxDB. All Rights Reserved.