Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a function in ruby

def mark_completed
      var_a = self.a
      self.check_something
    end

The other function is

def check_something(query = nil)
   raise 'Some_exception' if condition_a_satisfy?
      return true
 end

See , the function check_something is raising exception , What I want is : - "To catch the exception and return false somehow" How can i do it?

Note : - I cannot change my check_something function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
189 views
Welcome To Ask or Share your Answers For Others

1 Answer

Rescue RuntimeError in #mark_completed

When you call Kernel#raise with a string, you're actually raising the default exception, which is RuntimeError. You should catch that explicitly to avoid catching other exceptions that descend from StandardError unintentionally, or courting disaster by rescuing Exception which is almost never a good idea. For example:

def mark_completed
  self.check_something
rescue RuntimeError
  false
end

This will solve the question you asked in a controlled way, but deliberately side-steps the question of whether raising exceptions is the right thing for the code to do in the first place, or whether other refactorings are possible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...