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.

This time, after the exception is caught and handled, the program resumes executionafter the entire try statement that caught it—which is why we get the “continuing”message here. We don’t see the standard error message, and the program continues onits way normally.Exceptions can be raised by <strong>Python</strong> or by your program, and can be caught or not.To trigger an exception manually, simply run a raise statement (or an assert, whichis a conditional raise). User-defined exceptions are caught the same way as built-ins:>>> bad = 'bad'>>> try:... raise bad... except bad:... print 'got bad'...got badIf they’re not caught, user-defined exceptions are propagated up to the top-leveldefault exception handler, and terminate the program with a standard error message.In this case, the standard message includes the text of the string used to identify theexception:>>> raise badTraceback (most recent call last):File "", line 1, in ?raise badbadIn other cases, the error message may include text provided by classes used to identifyexceptions. As we’ll see in the next chapter, user-defined exceptions may bedefined with strings or classes, but class-based exceptions allow scripts to build exceptioncategories, inherit behavior, and have attached state information. Class-basedexceptions are preferred over strings today, and will be required as of <strong>Python</strong> 3.0:>>> class Bad(Exception): pass...>>> def doomed( ): raise Bad( )...>>> try:... doomed( )... except Bad:... print 'got Bad'...got Bad>>>Finally, try statements can include finally blocks. The try/finally combinationspecifies termination actions that always execute “on the way out,” regardless ofwhether an exception occurs in the try block:>>> try:... fetcher(x, 3)... finally:Exception Handling: The Short Story | 579

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

Saved successfully!

Ooh no, something went wrong!