Exception Handling

 
   

Ruby Way
By Hal Fulton
Slots : 1.0
Table of Contents
 


You may be used to using exceptions as a control structure in Python, but in Ruby they are meant to be for errors. Use catch/throw for a similar effect as a control structure.

In Ruby, raise is a method, not a statement. And while Python does not allow you to mix the try statement's except/else and finally forms, in Ruby you can combine the equivalents, rescue/else and ensure, in the begin/end block form.

 

 begin  f = File.new("somefile","r")  # do stuff... rescue Exception => details  puts "Could not open file! #{ details} " rescue  puts "Unforeseen error: #$!" else  puts "Finished task" ensure  f.close if f end 

The rescue clause is similar to Python's except, but there is a different exception hierarchy, which is always used. If you give a string as the first parameter, Ruby uses that as the message and uses RuntimeError as the default exception class.

Ruby does not necessarily raise the same-named exceptions as Python. For example, Ruby does not raise IOError above, which Python would have done. Consult a reference for Ruby's exception class hierarchy.

Ruby stores a reference to the resulting Exception object in the global variable $!, and you can use the => notation in the rescue clause to have it stored in another variable also. Ruby nests exceptions and does not forget them.

Ruby allows you to try to recover from an exception via either redo or retry, which are different. Care should be taken to avoid endless loops.


   

 

 



The Ruby Way
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2000
Pages: 119
Authors: Hal Fulton

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net