#class with rescue and raise in ruby program
class Question
attr_accessor :a1, :a2
def initialize(a1,a2)
@a1=rand(50)
@a2=rand(50)
end
def make_random_substraction
begin
puts 'Random Substraction of two numbers.'
puts "What is '#@a1' - '#@a2' ?"
@a3 = Integer(@a1) - Integer(@a2)
puts "#@a3"
if @a3<0
raise 'exception'
end
rescue
puts "An exception : answer is in negative value."
puts "Lets retry it in other order."
@a3 = Integer(@a2) - Integer(@a1)
puts "Here, answer is : #@a3"
end
end
end
obj=Question.new(@a1,@a2)
obj.make_random_substraction
class Question
attr_accessor :a1, :a2
def initialize(a1,a2)
@a1=rand(50)
@a2=rand(50)
end
def make_random_substraction
begin
puts 'Random Substraction of two numbers.'
puts "What is '#@a1' - '#@a2' ?"
@a3 = Integer(@a1) - Integer(@a2)
puts "#@a3"
if @a3<0
raise 'exception'
end
rescue
puts "An exception : answer is in negative value."
puts "Lets retry it in other order."
@a3 = Integer(@a2) - Integer(@a1)
puts "Here, answer is : #@a3"
end
end
end
obj=Question.new(@a1,@a2)
obj.make_random_substraction
OUTPUT:
Random Substraction of two numbers.
What is '18' - '1' ?
17
No comments:
Post a Comment
if you have any query regarding geek languages,
email on arora.ratul@gmail.com