[Tutor] exception details

Marilyn Davis marilyn at deliberate.com
Thu Mar 25 12:09:43 EST 2004


YES!  Thank you.  That's it.

Also, thank you for the reminder about random.choice!

Whew.

Lovely when things make sense again.

Marilyn

On Thu, 25 Mar 2004, Gregor Lingl wrote:

> 
> 
> Marilyn Davis schrieb:
> 
> >Hi,
> >
> >I'm trying to get a strong handle on exception mechanism details.
> >
> >Note that there are three try/except's and that the 1st 2 work
> >fine.  But the third one doesn't catch the random exception
> >generated.
> >
> >Do I have a typo?
> >
> >Thank you for any help you can give.
> >
> >Marilyn Davis
> >
> >#!/usr/bin/env python2.2
> >'''Ways to get more info about your caught exception.'''
> >
> >import exceptions # to get a list of built-in exceptions
> >...
> >
> 
> >   try:
> >        fun('''catch with "Exception, exception: on random exception doesn't work"''')
> >    except Exception, exception:
> >  
> >
> ########### here Exception has to be an expression that matches an exception
> ########### object that propagates from the try clause
> ########### in your code a string propagates from the try clause
> 
> >        print 'exception.args = ', exception.args
> >        print 'exception = ', exception
> >
> so I converted this string to an exception object
> (maybe there is a better way doing this than using eval)
> and now it works:
> 
> import exceptions # to get a list of built-in exceptions
> import random
> import sys  # gives info -- you can use the traceback module but
>             # it uses sys.
> 
> def ok(msg):
>     raise ValueError, msg
> 
> def fun(msg):
>     '''Raises a random built-in exception.'''
>     excepts = dir(exceptions)[:-2]
>     raise_this = random.choice(excepts) # a string
>     raise_this = eval(raise_this) # an exception object
>     print 'Raising', raise_this, 'To', msg
>     raise raise_this, msg
> 
> if __name__ == '__main__':
>     try:
>         ok('this works ok')
>     except Exception, exception:
>         print 'exception.args = ', exception.args
>         print 'exception = ', exception
>         print
> 
>     try:
>         fun('catch with "except:" on random exception works')
>     except:
>         print 'Caught: sys.exc_type =', sys.exc_type,\
>               'sys.exc_value =', sys.exc_value
>         print 'sys.exc_traceback =', sys.exc_traceback
>         print sys.exc_info()
>         print
> 
>     try:
>         fun('catch with "Exception, exception: on random exception does 
> equally work"')
>     except Exception, exception:
>         print 'exception.args = ', exception.args
>         print 'exception = ', exception
> 
> 
> Hope that gives you a clue (together with Python Docs, Library Reference 
> 2.4)
> Gregor
> 
> 

-- 




More information about the Tutor mailing list