ktulasi
Joined: 21 Oct 2009 Posts: 59
|
Posted: Mon Mar 22, 2010 1:50 pm Post subject: Exceptions in ruby |
|
|
Exception is a variable that raised or thrown when something goes wrong.If an exception i raised the program stops executing.
The ruby interpreter knows what the problem is,but doesnt know what to do after the problem occurred.It then checks for the code that can catch it.
The code that catches the exception variable is called Exception handler.
Types of exceptions are:
1.Runtime error
2.Compile time error.
Runtime error:these are the errors which can be handled.
Compile time error: these are the errors that cannot be handled.
Exceptions that raised can be handled in ruby using,
begin rescue end
where exception raises that code must be placed betweenbegin and rescue and where the exception handled be placed in rescue and end.
ex:
---
begin
file.open "document.rb"
rescue
puts" doc not found"
end
here if document.rb file not found then it will goes to resuce and puts "doc not found"
we can place any no.of rescues in begin and end block.
when an error arise it checks for the resue clause based on exception class.
def example
my_string = "what is this error for"
my_string.nonexistentmethod
rescue Exception:
puts "error occurred"
rescue NoMethodError:
puts "You're missing that method!"
else
puts "error"
end
in the example mystring.nonexistentmethod this is calling an un existent method.so it raises an exception then it checks for its corresponding class Here Exception handles it as it is the super class of all classes.
Ruby has some predefined classes - Exception and its children - that help you to handle errors that can occur in your program...
Exception
StandardError
ArgumentError
IOError
NameError
TypeError
NoMethodError
RangeError
RegExpError
The above are the some of the predefined classes of super class Exception.
Raise:Every ruby library raises an exception if any error occurs, and you can raise exceptions explicitly in your code too. To raise an exception, use raise. It takes one argument, which should be a string that describes the exception.and the other argument as our own text message.
example:
class User
def user_details(data)
if (gender !="Female")
raise "you entered wrong"
end
end
end
a=User.new
a.user_details("male")
we can create our own exception classes.
it is like,
in one rb file take a class and inherit a predefined class
1.rb
-----
class GenderError < Exception
end
predefined class can be any class.
and in other rb file take
2.rb
----
class User
include 1.rb
def gender(data)
if gender != "Female" & gender !="Male"
raise GenderError.new , "Invalid input"
end
end
end
a=User.new
a.gender("abc")
here we are creating an object for GenderError . |
|