Section 2.16. Errors and Exceptions


2.16. Errors and Exceptions

Syntax errors are detected on compilation, but Python also allows for the detection of errors during program execution. When an error is detected, the Python interpreter raises (aka throws, generates, triggers) an exception. Armed with the information that Python's exception reporting can generate at runtime, programmers can quickly debug their applications as well as fine-tune their software to take a specific course of action if an anticipated error occurs.

To add error detection or exception handling to your code, just "wrap" it with a TRy-except statement. The suite following the TRy statement will be the code you want to manage. The code that comes after the except will be the code that executes if the exception you are anticipating occurs:

  try:      filename = raw_input('Enter file name: ')      fobj = open(filename, 'r')      for eachLine in fobj:          print eachLine,      fobj.close()   except IOError, e:        print 'file open error:', e


Programmers can explicitly raise an exception with the raise command. You can learn more about exceptions as well as see a complete list of Python exceptions in Chapter 10.



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net