Ruby/Statement/raise

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

raise ArgumentError

def join_to_successor(s)
  raise ArgumentError, "No successor method!" unless s.respond_to? :succ
  return "#{s}#{s.succ}"
end
join_to_successor("a")                # => "ab"
join_to_successor(4)                  # => "45"
join_to_successor(4.01)
# ArgumentError: No successor method!



Raise exception from constructor

class Person
  def initialize(name)
    raise ArgumentError, "No name present" if name.empty?
  end
end
fred = Person.new("")



Raise IndexError

  class MyCapacity
    include Comparable
    attr :volume
    def initialize(volume)
      @volume = volume
    end
    def inspect
      "#" * @volume
    end
    def <=>(other)
      self.volume <=> other.volume
    end
    def succ
      raise(IndexError, "Volume too big") if @volume >= 9
      MyCapacity.new(@volume.succ)
    end
  end



raise one on your own with the raise method from Kernel

bad_dog = true
if bad_dog
  raise StandardError, "bad doggy"
else
  arf_arf
end



Raising Exceptions

raise "An error has occurred"