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.

Chapter 27CHAPTER 27Exception Basics27This last part of the book deals with exceptions, which are events that can modify theflow of control through a program. In <strong>Python</strong>, exceptions are triggered automaticallyon errors, and can be triggered and intercepted by your code. They areprocessed by four statements we’ll study in this part, the first of which has two variations(listed separately here), and the last of which is an optional extension until<strong>Python</strong> 2.6:try/exceptCatch and recover from exceptions raised by <strong>Python</strong>, or by you.try/finallyPerform cleanup actions, whether exceptions occur or not.raiseTrigger an exception manually in your code.assertConditionally trigger an exception in your code.with/asImplement context managers in <strong>Python</strong> 2.6 and later (optional in 2.5).This topic was saved for this last part of the book because you need to know aboutclasses to code exceptions of your own. With a few exceptions (pun intended),though, you’ll find that exception handling is simple in <strong>Python</strong> because it’s integratedinto the language itself as another high-level tool.One procedural note up front: the exception story has changed in two major wayssince this book was first written—the finally clause can now appear in the same trystatement as except and else clauses, and user-defined exceptions should now becoded as class instances not strings. I will describe both the old and new ways ofdoing things in this edition, because you are still very likely to see the original techniquesin code for some time to come. Along the way, I’ll point out how things haveevolved in this domain. I’ll also document the new with statement, even though itsofficial appearance is still one release in the future.575

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

Saved successfully!

Ooh no, something went wrong!