Exception Handiling

Hello,

I have a basic idea of what an exception is but I am not able to
understand it so that I can make use of it in my application’s.
If possible please try and help me out with the basic of exception and
its use.

It would also be great, if any one of you could give me certain links on
exceptions which would help me understand its concepts better.

Thank You

typical exception look as below:

begin
raise Exception.new("")
rescue Exception => x
puts x.message
rescue
puts "an error has occured
end

if an exception is raised then all code after is skipped up to the
rescue which rescues the program.

if an exception is called outside a begin block the exception will be
raised up the stack until a rescue block is found. classes may declare a
rescue_method that wild catch exceptions raised by any method in the
class.

Exceptions are meant to be use when errors occur that directly impact
the program. For instance if a configuration file is missing that will
throw an exception were as if the file is part of a user input and isn’t
expected to be there then normal error handling would be appropriate.

It would also be great, if any one of you could give me certain links on
exceptions which would help me understand its concepts better.

http://ruby.activeventure.com/programmingruby/book/tut_exceptions.html

…some arbitrary simple example i can think of; say you have a
ActiveRecord model Item with records in the db ranging from 1-100, and u
search for #101:

class ItemController

def example
Item.find(101) # this raises an exception
rescue ActiveRecord::RecordNotFound # this will catch this specific
exception
flash[:notice]=“the record was not found!”
redirect_to :other_action
end

end

in this example instead of the app crashing since no record was found,
we send a message to the user via the other_action+flash message.

the syntax of the rescue clauses are pretty simple; if you have the name
of the Exception you can rescue that SPECIFIC exception like the example
above.

if you want to catch any old exception (doesn’t matter what the reason
is) you can just write “rescue” without anything appended.

you can also do multiple resuces, with each rescue rescuing a certain
exception type.

hope the link helps out too.
good luck!

http://ruby.activeventure.com/programmingruby/book/tut_exceptions.html