auralbee
auralbee

Reputation: 8841

Error handling: How to throw/catch errors correctly

I have a method that calls two other methods:

def first_method
  second_method

  # Don´t call this method when something went wrong before
  third_method
end

The second_method calls other methods:

def second_method
  fourth_method
  fifth_method
end

Let´s say the fifth_method has a begin/rescue statement:

def fifth_method
  begin
    # do_something
  rescue Error => e
    # 
  end
end

Now I want to avoid third_method to be called when fifth_method throws an error. How would I/you solve this most elegantly in Ruby.

Upvotes: 1

Views: 265

Answers (3)

Stefan
Stefan

Reputation: 114258

If you don't want to use exceptions, you can just return a status:

def fifth_method
  # do_something
  true
rescue Error => e
  false
end

def first_method
  if second_method
    third_method
  end
end

Upvotes: 1

megas
megas

Reputation: 21791

It seems to me so obvious but anyway

def first_method
  begin 
    second_method
  rescue
    return
  end
  third_method
end

This construction (without explicit type of exception) will catch StandartError exception.

To avoid intersection with another exceptions you can create your own exception class:

class MyError < StandardError; end

and then use it

begin 
  second_method
rescue MyError => e
  return
end

Note that you should not inherit exception from Exception because this type of exceptions are from environment level, where the exceptions of StandardError are meant to deal with application level errors.

Upvotes: 3

Thomas Tran
Thomas Tran

Reputation: 467

I think the simplest way is removing error catching from fifth_method and move it to the first_method

def first_method
  begin 
     second_method

     third_method
  rescue Error => e

  end
end


def fifth_method
   # do_something

end

Upvotes: 1

Related Questions