Error Handling


Error handling in Python is done through the use of exceptions that are caught in try blocks and handled in except blocks. If an error is encountered, a TRy block code execution is stopped and transferred down to the except block, as shown in the following syntax:

try:     f = open("test.txt") except IOError:     print "Cannot open file."


The exception type value refers to either one of the built-in Python exceptions or a custom-defined exception object. The error value is a variable to capture the data returned by the exception.

Note

The TRy block also supports the use of an else block after the last except block. The else block is executed if the TRy block finishes without receiving an exception.


In addition to using an except block after the try block, you can also use the finally block. The code in the finally block will be executed regardless of whether an exception occurs. If no exception occurs, the finally block will be executed after the try block. If an exception occurs, the execution immediately is transferred to the finally block, and then the exception continues until it is handled. The following code shows an example of using finally to force a file to be closed even if an exception occurs:

f = open("test.txt") try:     f.write(data)     . . . finally:     f.close()


You can raise an exception in your own program by using the raise exception [, value] statement. The value of exception is one of the built-in Python exceptions or a custom-defined exception object. The value of value is a Python object that you create to give details about the exception. Raising an exception breaks current code execution and returns the exception back until it is handled. The following example shows how to raise a generic RuntimeError exception with a simple text message value:

raise RuntimeError, "Error running script"


Note

If the exception is not handled, the program terminate and a trace of the exception is sent to sys.stderr.




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

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