Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having Exception handling as a common method in Ruby

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?

like image 716
sameera207 Avatar asked Sep 15 '11 16:09

sameera207


1 Answers

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 
like image 185
Vlad Khomich Avatar answered Oct 20 '22 01:10

Vlad Khomich