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.

Notice that this class’ _ _exit_ _ method returns False to propagate the exception;deleting the return statement there would have the same effect, as the default Nonereturn value of functions is False by definition. Also, notice how the _ _enter_ _method returns self as the object to assign to the as variable; in other use cases, thismight return a completely different object instead.When run, the context manager traces the entry and exit of the with statement blockwith its _ _enter_ _ and _ _exit_ _ methods:% python withas.pystarting with blockrunning test 1reachedexited normallystarting with blockrunning test 2raise an exception! Traceback (most recent call last):File "C:/<strong>Python</strong>25/withas.py", line 22, in raise TypeErrorTypeErrorContext managers are somewhat advanced devices that are not yet officially part of<strong>Python</strong>, so we’ll skip additional details here (see <strong>Python</strong>’s standard manuals for thefull story—for example, a new contextlib standard module provides additional toolsfor coding context managers). For simpler purposes, the try/finally statement providessufficient support for termination-time activities.Chapter SummaryIn this chapter, we began our look at exception processing by exploring the statementsrelated to exceptions in <strong>Python</strong>: try to catch them, raise to trigger them,assert to raise them conditionally, and with to wrap code blocks in context managersthat specify entry and exit actions.So far, exceptions probably seem like a fairly lightweight tool, and in fact, they are;the only substantially complex thing about them is how they are identified. The nextchapter continues our exploration by describing how to implement exception objectsof your own; as you’ll see, classes allow you to code more useful exceptions thansimple strings today. Before we move ahead, though, work though the followingshort quiz on the basics covered here.600 | Chapter 27: Exception Basics

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

Saved successfully!

Ooh no, something went wrong!