[wingide-users] Stop on exception, within try block?

Wing IDE Support support at wingware.com
Wed Feb 26 15:13:20 EST 2014


On 2/26/14, 7:33 AM, Graham Wideman wrote:
> But, as I expected (and you note) turning on Always results in a large number of exception stops from startup code and included libraries even before my own code is reached. So not terribly usable.
>
> So I guess I would like to know what the prospects are for an option that acts like "Always", but only for selected code regions -- for example "all modules open in the IDE", or "modules that are flagged" or somesuch.

I can see this mode being useful and we'll look into implementing it -- 
offhand I can't recall if the ceval bytecode loop provides enough hooks 
to do this easily.

What we use is a function that will log exceptions, but will also call 
sys.except_hook if run in the debugger.  The function is basically (I'm 
simplifying here and haven't run this exact version so minor errors may 
have crept in):

def ReportCurrentException():
   """ Reports the current exception. """

   # Report in wing's debugger
   if 'WINGDB_ACTIVE' in os.environ:
     sys.excepthook(*sys.exc_info())

   traceback.print_exc()

Usage is basically:

   try:
     f = open(filename, 'r')
   except IOError:
     ReportCurrentException()
     f = None

We also have a decorator to log all exceptions in a callable:

class log_exceptions(object):
   """ Decorator class that will catch exceptions from the function it
   wraps and return the given value. """

   def __init__(self, exc_return_val):
     """ Create the decorator.  exc_return_val is the value to return
     on exception. """

     self.exc_return_val = exc_return_val
     self.exc_call = exc_call

   def __call__(self, func):
     """ Excecuted when decorator applied to wrapped function. """

     # Bind vals to locals so self can disappear
     exc_return_val = self.exc_return_val
     exc_call = self.exc_call

     @functools.wraps(func)
     def wrapper(*args, **kw):
       try:
         return func(*args, **kw)
       except Exception:
         ReportCurrentException()

         return copy.deepcopy(exc_return_val)

     return wrapper

Example:
   @log_exceptions(None)
   def try_open(filename, mode):
     return open(filename, mode)

The above has worked reasonably well for us.

Cheers,

John



More information about the wingide-users mailing list