Ruby Exceptions

Watch out! This tutorial is over 3 years old. Please keep this in mind as some code snippets provided may no longer work or need modification to work on current systems.
Tutorial Difficulty Level    

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.

# Count and report the number of lines and characters in a file.
print "File name: "
fn = gets.chomp
begin
    f = open(fn)
    nlines = 0
    length = 0
    f.each { |line| nlines += 1; length += line.length }
rescue
    print "File read failed: " + $! + "\n"
else
    print fn, ": ", nlines, " lines, ", length, " characters.\n"
end