Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

Error Processing in Python

Uploaded by

SANJAY
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Error Processing in Python

Uploaded by

SANJAY
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Error reporting and processing through exceptions is one of

Python’s key features. Care must be taken when handling exceptions


to ensure proper application cleanup while maintaining useful
error reporting. Unlike C, where the common way to report errors is
through function return values that then have to be checked on every
invocation, in Python a programmer can raise an exception at any point
in a program. When the exception is raised, program execution is
interrupted as the interpreter searches back up the stack to find a
context with an exception handler. This search algorithm allows error
handling to be organized cleanly in a central or high-level place
within the program structure. Libraries may not need to do any
exception handling at all, and simple scripts can frequently get away
with wrapping a portion of the main program in an exception handler to
print a nicely formatted error. Proper exception handling in more
complicated situations can be a little tricky, though, especially in
cases where the program has to clean up after itself as the exception
propagates back up the stack.

Throwing and Catching


The statements used to deal with exceptions are raise and
except. Both are language keywords. The most common form of
throwing an exception with raise uses an instance of an exception
class.

#!/usr/bin/env python
def throws():
raise RuntimeError('this is the error message')
def main():
throws()
if __name__ == '__main__':

main()

The arguments needed by the exception class vary, but usually include
a message string to explain the problem encountered.

1
If the exception is left unhandled, the default behavior is for the
interpreter to print a full traceback and the error message included
in the exception.

Logging Exceptions
For daemons or other background processes, printing directly to stderr
may not be an option. The file descriptor might have been closed, or
it may be redirected somewhere that errors are hard to find. A better
option is to use the logging module to log the error, including the
full traceback.

Cleaning Up and Re-raising


In many programs, simply reporting the error isn’t enough. If an
error occurs part way through a lengthy process, you may need to undo
some of the work already completed. For example, changes to a
database may need to be rolled back or temporary files may need to be
deleted. There are two ways to handle cleanup operations, using a
finally stanza coupled to the exception handler, or within an
explicit exception handler that raises the exception after cleanup is
done.

For cleanup operations that should always be performed, the simplest


implementation is to use try:finally. The finally stanza is
guaranteed to be run, even if the code inside the try block raises
an exception.

2
Re-raising Exceptions
Sometimes the cleanup action you need to take for an error is
different than when an operation succeeds. For example, with a
database you may need to rollback the transaction if there is an error
but commit otherwise. In such cases, you will have to catch the
exception and handle it. It may be necessary to catch the exception
in an intermediate layer of your application to undo part of the
processing, then throw it again to continue propagating the error
handling.

Preserving Tracebacks
Frequently the cleanup operation itself introduces another opportunity
for an error condition in your program. This is especially the case
when a system runs out of resources (memory, disk space, etc.).
Exceptions raised from within an exception handler can mask the
original error if they aren’t handled locally.

You might also like