Ruby/Statement/raise
Материал из Wiki.crossplatform.ru
(Различия между версиями)
ViGOur (Обсуждение | вклад) м (1 версия: Импорт выборки материалов по Ruby) |
Текущая версия на 18:00, 13 сентября 2010
Содержание |
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"