MC logo

Exceptions I

  Ruby Example Code

<<Methods III exc1.rb Regular Expressions I>>
# Count and report the number of lines and characters in a file.
print "File name: "
fn = gets.chomp
    f = open(fn)
    nlines = 0
    length = 0
    f.each { |line| nlines += 1; length += line.length }
    print "File read failed: " + $! + "\n"
    print fn, ": ", nlines, " lines, ", length, " characters.\n"
See:Programming RubyRuby User's GuideRuby Manual

Ruby uses exceptions. Instead of try, the block is called begin, and instead of catch there is rescue. The else is executed when no exception occurs. There is also an ensure block which is always run last, exception or no.
<<Methods III Regular Expressions I>>