Home > Articles > Open Source > Python

  • Print
  • + Share This
This chapter is from the book

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.

  • + Share This
  • 🔖 Save To Your Account