Ruby Exception Handling
Exception is unreliable condition which are occurred during the program execution. This unwanted condition are disturbed the program execution process and abnormally terminate program execution. So this are not good to programmer and user perspective.
Ruby programming are providing a controlling mechanism which are capable to handle unwanted situation. And defining rules which are handle custom and system exception this is called Exception handling. Let see an example.
puts "Running Code"
#Suppose error are occurred
raise 'Getting Error'
puts "End Code"
Output
Running Code
exception.rb:3:in `<main>': Getting Error (RuntimeError)
raise method are create an exception of RuntimeError type this method are exist in kernel module. And when error are occurred and not handling this error then the program are terminated. Let see an example of, how to control exception in Ruby programming.
def checkTest(parms)
begin
puts 'Check Test'
#define of custom test case condition of exception
if parms.class== NilClass or parms.class == String
raise ArgumentError,'ArgumentError has occured.'
end
#work when parms are not zero
puts "Result : #{10/parms}";
puts 'All Test Case Valid'
rescue ArgumentError
puts 'Invalid Value are pass'
rescue ZeroDivisionError
puts 'Zero By Zero Error'
end
puts "-----------"
end
checkTest(2)
checkTest(nil)
checkTest("Two")
checkTest(0)
Output
Check Test
Result : 5
All Test Case Valid
-----------
Check Test
Invalid Value are pass
-----------
Check Test
Invalid Value are pass
-----------
Check Test
Zero By Zero Error
-----------
In this program is capable to handle three type of exception. First is given argument is form of an nil object, when argument of method is form of String, and when number is divide by zero.
Predefined Exception List
Exception |
---|
SyntaxError |
NameError |
NoMethodError |
LoadError |
FloatDomainError |
RuntimeError |
ThreadError |
NotImplementedError |
ArgumentError |
TypeError |
EOFError |
ThreadError |
ZeroDivisionError |
SystemStackError |
SystemExit |
Custom Exception Handling
#implement custom exception
def my_exception
begin
raise 'A simple exception'
rescue StandardError => e
puts e.backtrace.inspect
puts e.message
end
end
# calling method
my_exception
["test.rb:4:in `exception'", "test.rb:13:in `<main>'"]
A simple exception
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment