Reputation: 16619
Can someone tell me is there a way to make the exception handling as a common method and use it inside a methods? Let me explain it further.
For example, I have following methods
def add(num1, num2)
begin
num1 + num2
rescue Exception => e
raise e
end
end
def divide(num1, num2)
begin
num1 / num2
rescue Exception => e
raise e
end
end
As you can see, even though my method needs only one line, because of the exception handling code, the method gets bigger.
What I'm looking for is a more slimmer solution like (just a thought)
def add(num1, num2)
num1 + num2 unless raise_exception
end
def divide(num1, num2)
num1 / num2 unless raise_exception
end
def raise_exception
raise self.Exception
end
Please note the above code doesn't work, just my idea. Is this possible or is there any other good way?
Upvotes: 13
Views: 3425
Reputation: 2331
def handle_exception(&block)
yield
rescue Exception => e
raise e
end
def add(num1, num2)
handle_exception { num1 + num2 }
end
def divide(num1, num2)
handle_exception { num1 / num2 }
end
Upvotes: 14
Reputation: 27845
Why do you rescue an Exception and raise it afterwords? Your calling routine must rescue again your exception.
You could do:
def divide(num1, num2)
num1 / num2
end
begin
divide(1,0)
rescue Exception => e
puts "Exception '#{e}' occured"
end
You may rescue the Exception in one line:
def divide2(num1, num2)
num1 / num2 rescue Exception
end
p divide2(6,3) # -> 2
p divide2(1,0) # -> Exception
But then you will loose the information which Exception occured.
Upvotes: 0
Reputation: 5880
yep, something like that:
def try
yield
rescue Exception => e
puts 'I`m rescued'
end
def devide(num1, num2)
try { num1/num2 }
end
ruby-1.9.2-p180 :013 > devide(5,1)
=> 5
ruby-1.9.2-p180 :014 > devide(5,0)
I`m rescued
=> nil
Upvotes: 6
Reputation: 160171
Sure, you could pass a block in to a method that yields inside the begin section.
Upvotes: 0