[Tutor] exception details
Marilyn Davis
marilyn at deliberate.com
Wed Mar 24 19:08:53 EST 2004
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
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)
while excepts[-1][0] == '_':
# Getting rid of __doc__ and __name__
excepts.pop()
raise_this = excepts[random.randrange(len(excepts))]
print 'Raising', str(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
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()
try:
fun('''catch with "Exception, exception: on random exception doesn't work"''')
except Exception, exception:
print 'exception.args = ', exception.args
print 'exception = ', exception
############################################################
# OUTPUT:
# bash-2.05a$ ./x.py
# exception.args = ('this works ok',)
# exception = this works ok
# Raising UnboundLocalError To catch with "except:" on random exception works
# Caught: sys.exc_type = UnboundLocalError sys.exc_value = catch with "except:" on random exception works
# sys.exc_traceback = <traceback object at 0x81522f4>
# ('UnboundLocalError', 'catch with "except:" on random exception works', <traceback object at 0x81522f4>)
# Raising Exception To catch with "Exception, exception: on random exception doesn't work"
# Traceback (most recent call last):
# File "./x.py", line 37, in ?
# fun('''catch with "Exception, exception: on random exception doesn't work"''')
# File "./x.py", line 19, in fun
# raise raise_this, msg
# Exception: catch with "Exception, exception: on random exception doesn't work"
# bash-2.05a$
--
More information about the Tutor
mailing list