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. 

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…