Thursday, September 2, 2010

Exception Handling in Python

quoted directly from Doug Hellman


#!/usr/bin/env python

import sys
import traceback

def throws():
raise RuntimeError('error from throws')

def nested():
try:
throws()
except Exception, original_error:
try:
raise
finally:
try:
cleanup()
except:
pass # ignore errors in cleanup

def cleanup():
raise RuntimeError('error from cleanup')

def main():
try:
nested()
return 0
except Exception, err:
traceback.print_exc()
return 1

if __name__ == '__main__':
sys.exit(main())


This construction prevents the original exception from being overwritten by the latter, and preserves the full stack in the traceback.

No comments:

Post a Comment

comment: