How to Raise an Exception with Ruby on Rails
Ruby provides built in mechanism for raising an error. All you have to do is to call raise method and it will stop your program from executing. The flow of your program will stop where you declare raise method in your code.
def raise_my_error
puts “line of text 1”
raise
puts “line of text 2”
end
raise_my_error //call to your method will print “line of text 1” but not “line of text 2”
Raise method create an instance of an Exception when called. In fact an Exception class is a superclass for subclasses such as StandardError and RuntimeError. It is possible to raise an error of specific class by passing with one of the argument.
def calc(x)
raise ArgumentError, “Argument is not a number” unless x.is_a? Numeric
2*x
end
It is important to not one distinction between errors in Ruby and other programming languages. Errors are not thrown but rather raised.