180 likes | 298 Views
Exceptions. CIT 383: Administrative Scripting. Topics. Subclasses and Inheritance What is an Exception? Raising Exceptions Catching Exceptions Retry Exception Classes. Subclassing. A subclass is a class that is based on but modified from an existing class.
E N D
Exceptions CIT 383: Administrative Scripting CIT 383: Administrative Scripting
CIT 383: Administrative Scripting Topics • Subclasses and Inheritance • What is an Exception? • Raising Exceptions • Catching Exceptions • Retry • Exception Classes
CIT 383: Administrative Scripting Subclassing A subclass is a class that is based on but modified from an existing class. • A subclass extends another class. • Extends means the same as inherits from. • The original class is known as the superclass. A subclass is defined using < superclass: class Point3D < Point end
CIT 383: Administrative Scripting Inheritance Subclasses inherit methods of superclass. Superclass methods can be called on subclass. p3d = Point3D.new(0,0,0) p3d.x p3d.y Class variables shared with superclass. If subclass modifies value of a class variable, the superclass sees the modified value too.
CIT 383: Administrative Scripting Overiding and Adding Methods To make Point3D useful, redefine initialize: class Point3D < Point def initialize(x,y,z) @x,@y,@z = x,y,z end We also need to add accessors for the z coordinate: def z @z end def z=(value) @z = value end end
CIT 383: Administrative Scripting Calling Superclass Methods How can you call an overidden method? Use super(args) in method of subclass. New definition of initialize: class Point3D < Point def initialize(x,y,z) # pass first two args to # superclass initialize method super(x,y) # initialize the third argument @z = z end end
CIT 383: Administrative Scripting What is an Exception? An exception is an object that represents an exceptional condition, such as an error of some type. An exception is raised when an error occurs. A ruby program terminates on an exception. An exception can be caught by an exception handler, preventing program termination.
CIT 383: Administrative Scripting Exception Classes Exceptions belong to Exception class or its subclasses. Exception NoMemoryError SystemExit StandardError ArgumentError IOError IndexError TypeError ZeroDivisionError
CIT 383: Administrative Scripting Raising Exceptions The raise method raises an exception raise: creates a new RuntimeError and raises it. raise(string): creates new RuntimeError with the specified string as its message and raises it. raise(class): creates a new exception object of the specified class and raises it. raise(class, string): creates a new exception object of the specified class with the specified string as its message and raises it.
CIT 383: Administrative Scripting Raise Example Raise an exception on a bad username argument: class User def initialize(username) if username =~ /^[a-z][a-z0-9]+$/ @username = username else raise 'Invalid username' end end end
CIT 383: Administrative Scripting Handling Exceptions Use a rescue clause with a begin statement. begin # Ruby code that may raise # an exception. rescue # Exception-handling code. end
CIT 383: Administrative Scripting Handling Exceptions by Type Specify the exception class after rescue By default, only StandardError is caught. To catch any exception rescue Exception To catch specific exception and assign to e. rescue ArgumentError => e Accessing the exception object string puts e.message
CIT 383: Administrative Scripting Catching Multiple Exception Types Handling multiple types identically: rescue ArgumentError, IOError => e Handling each type differently: begin #code that may raise exception rescue ArgumentError => e # code to handle ArgumentErrors rescue IOError => e # code to handle IOErrors end
CIT 383: Administrative Scripting Retry Retry restarts at top of begin block. # Try to get URL up to 10 times in case svr slow tries = 0 begin tries += 1 geturl(‘http://example.com/’) rescue Exception => e puts e.message # print error if tries < 10 sleep(10) # wait 10 seconds retry # try get_url again end end
CIT 383: Administrative Scripting Writing Exception Handlers Keep begin blocks short. begin # no more than 3 lines rescue end Move longer blocks into a new method. begin try_to_geturl() rescue end
CIT 383: Administrative Scripting Defining Exceptions What is the purpose of exception classes? Each class can be handled differently by its own rescue block. Creating a new exception class class MyError < StandardError end Exception subclasses define no new methods Only characteristics that matter are their name and parent class.
CIT 383: Administrative Scripting Defining Exceptions Create a new exception class only when The caller has to do something different to recover from the error. Do not create a class for each error message Use the message string to contain the message instead of creating a new exception class.
CIT 383: Administrative Scripting References • Michael Fitzgerald, Learning Ruby, O’Reilly, 2008. • David Flanagan and Yukihiro Matsumoto, The Ruby Programming Language, O’Reilly, 2008. • Hal Fulton, The Ruby Way, 2nd edition, Addison-Wesley, 2007. • Robert C. Martin, Clean Code, Prentice Hall, 2008. • Dave Thomas with Chad Fowler and Andy Hunt, Programming Ruby, 2nd edition, Pragmatic Programmers, 2005.