Exception

From RubySpec

Jump to: navigation, search

From ruby-doc "Descendents of class Exception are used to communicate between raise methods and rescue statements in begin/end blocks. Exception objects carry information about the exception—its type (the exception‘s class name), an optional descriptive string, and optional traceback information. Programs may subclass Exception to add additional information."

Example of using the instance method backtrace from ruby-doc:

  def a
    raise "boom"
  end
  def b
    a()
  end
  begin
    b()
  rescue => detail
    print detail.backtrace.join("\n")
  end


Another example of using exceptions:

 irb(main):001:0> class Sample
 irb(main):002:1> def initialize
 irb(main):003:2> @ary = [1,2,3,4,5]
 irb(main):004:2> end
 irb(main):005:1> def each
 irb(main):006:2> begin
 irb(main):007:3* @ary.each {|i| yield i}
 irb(main):008:3> rescue LocalJumpError
 irb(main):009:3> print "Whoops, no block given. Please provide a block"
 irb(main):010:3> end
 irb(main):011:2> end
 irb(main):012:1> end
 => nil
 irb(main):013:0> s = Sample.new
 => #<Sample:0x3347a8 @ary=[1, 2, 3, 4, 5]>
 irb(main):014:0> s.each
 Whoops, no block given. Please provide a block=> nil
Personal tools