Error Processing in Python
Error Processing in Python
#!/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.
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.