12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

aise instanceraise class, instance# Same as: raise instance._ _class_ _, instance# Matches except with this class or its superclassraise# Reraises the current exceptionThe third of these is the most commonly used form today. For class-based exceptions,<strong>Python</strong> always requires an instance of the class. Raising an instance reallyraises the instance’s class; the instance is passed along with the class as the extra dataitem (as we’ve seen, it’s a good place to store information for the handler). For backwardcompatibility with <strong>Python</strong> versions in which built-in exceptions were strings,you can also use these forms of the raise statement:raise class # Same as: raise class( )raise class, arg# Same as: raise class(arg)raise class, (arg, arg, ...) # Same as: raise class(arg, arg, ...)These are all the same as saying raise class(arg...), and therefore the same as theraise instance form above. Specifically, if you list a class instead of an instance, andthe extra data item is not an instance of the class listed, <strong>Python</strong> automatically callsthe class with the extra data items as constructor arguments to create and raise aninstance for you.For example, you can raise an instance of the built-in KeyError exception by sayingsimply raise KeyError, even though KeyError is now a class; <strong>Python</strong> calls KeyError tomake an instance along the way. In fact, you can raise a KeyError, and any otherclass-based exception, in a variety of ways:raise KeyError( )raise KeyError, KeyError( )raise KeyErrorraise KeyError, "bad spam"# Normal form: raise an instance# Class, instance: use instance# Class: an instance will be generated# Class, arg: an instance will be generatedFor all of these raise forms, a try statement of the form:try:...except KeyError, X:...assigns X to the KeyError instance object raised.If that sounds confusing, just remember that exceptions may be identified by stringor class instance objects. For strings, you may pass extra data with the exception ornot. For classes, if there is no instance object in the raise statement, <strong>Python</strong> makesan instance for you.In <strong>Python</strong> 2.5, you can almost ignore the string forms of raise altogether becausestring-based exceptions generate warnings, and will be disallowed in a future release.But alas, backward compatibility still counts in books that teach a programming languagebeing used by more than one million people today!614 | Chapter 28: Exception Objects

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!