Ruby/Statement/rescue

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

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

Содержание

begin

    names=IO.readlines("C:\\customer_details1.txt")
    count=names.length
    for i in 0...count
         puts "The contents of the file are #{names[i]}"
    end
    rescue
         $stderr.puts "error"
         puts "The error occurred is #{$!}"
end



C++, Java, and Ruby exception handling compared

C++             Java                  Ruby
try {}          try {}                begin/end
catch {}        catch {}              rescue keyword (or catch method)
Not applicable  finally               ensure
throw           throw                 raise (or throw method)



==Handling Exceptions:/td>




begin
  puts 10 / 0
rescue
  puts "You caused an error!"
end



Handling Passed Exceptions

begin
  puts 10 / 0
rescue => e
  puts e.class
end



how exceptions work in Ruby.

begin
    eval "12 / 0"
rescue ZeroDivisionError
    puts "Oops. You tried to divide by zero again."
    exit 1
ensure
    puts "Tsk. Tsk."
end



rescue"s syntax makes handling different exceptions in different ways easy:

begin
  ... code here ...
rescue ZeroDivisionError
  ... code to rescue the zero division exception here ...
rescue YourOwnException
  ... code to rescue a different type of exception here ...
rescue
  ... code that rescues all other types of exception here ...
end