Attachment 'exc_wrap.py'

Download

   1 import sys
   2 
   3 
   4 class WrapperException(Exception):
   5     def __init__(self, msg):
   6         Exception.__init__(self, msg)
   7         self.info = sys.exc_info()
   8         
   9     def unwrap(self):
  10         """ unwrap the original exception data
  11         
  12         Return tuple (type, value, list)
  13         
  14         The list contain the complete stack up to the wrapped
  15         exception, excluding the frame of the wrapper itself. The list
  16         can be formatted using traceback.format_list.
  17         """
  18         import traceback
  19         stackUpToWrapper = traceback.extract_tb(sys.exc_info()[2])[:-1]
  20         type, value, tb = self.info
  21         wrappedStack = traceback.extract_tb(tb)
  22         del tb
  23         return type, value, stackUpToWrapper + wrappedStack
  24 
  25 
  26 def first():
  27     second()
  28     
  29 def second():
  30     third()
  31     
  32 def third():
  33     # Wrap exceptions 
  34     try:
  35         forth()
  36     except ValueError:
  37         raise WrapperException('Fatal error! Try to be more carful '
  38                                'with your splits.')
  39                                
  40 def forth():
  41     lowLevel()
  42                                
  43 def lowLevel():
  44     # Error at low level    
  45     a, b = ''.split()
  46  
  47 try:
  48     first()
  49 except WrapperException, wrapper:
  50     import traceback
  51     # Show the wrapper exception
  52     traceback.print_exc()
  53     print
  54     
  55     # Show the wrapped exception
  56     type, value, list = wrapper.unwrap()
  57     print 'Traceback (most recent call last):'
  58     print ''.join(traceback.format_list(list))
  59     print ''.join(traceback.format_exception_only(type, value))
  60     

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.
  • [get | view] (2005-04-20 00:34:11, 1.5 KB) [[attachment:exc_wrap.py]]
 All files | Selected Files: delete move to page copy to page

You are not allowed to attach a file to this page.