- 2.1 Program Output, the print Statement, and Hello World!
- 2.2 Program Input and the raw_input()Built-in Function
- 2.3 Comments
- 2.4 Operators
- 2.5 Variables and Assignment
- 2.6 Numbers
- 2.7 Strings
- 2.8 Lists and Tuples
- 2.9 Dictionaries
- 2.10 Code Blocks Use Indentation
- 2.11 if Statement
- 2.12 while Loop
- 2.13 for Loop and the range() Built-in Function
- 2.14 List Comprehensions
- 2.15 Files and the open() and file() Built-in Functions
- 2.16 Errors and Exceptions
- 2.17 Functions
- 2.18 Classes
- 2.19 Modules
- 2.20 Useful Functions
- 2.21 Exercises
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.