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?
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 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With