Re: [Tutor] exception question

Magnus Lycka magnus at thinkware.se
Wed Apr 28 09:51:12 EDT 2004


Dave S wrote:
> Is it possible, for the code after except to know the exception type. I 
> know I can do multiple "except"s for each condition but this is not 
> realy what I want.

But that's usually the right thing to do! ;)

> try:
>     ....
>     ...code...
>     ....
> except:

You should avoid these kinds of unqualified except blocks, since you
can't really treat errors you never thought would occur. If you must
have one except block, make sure to do "raise" without any arguments
if you didn't figure out what error you had and how to handle it.

Silencing error that you aren't really in control of is a quick way
of making programming slow and difficult...

>     ...code ....

>>> def expr(f):
        try:
                f()
        except Exception, e:
            print "I got a", e.__class__, "which said:"
            print e
            print "It has these attributes:", dir(e)
            print "And it was called with", e.args

		
>>> def z():
        1/0

	
>>> expr(z)
I got a exceptions.ZeroDivisionError which said:
integer division or modulo by zero
It has these attributes: ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args']
And it was called with ('integer division or modulo by zero',)
>>> def x():
        [][9]

	
>>> expr(x)
I got a exceptions.IndexError which said:
list index out of range
It has these attributes: ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args']
And it was called with ('list index out of range',)
>>> def r():
        raise StandardError("Python", "is", "nice")

>>> expr(r)
I got a exceptions.StandardError which said:
('Python', 'is', 'nice')
It has these attributes: ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args']
And it was called with ('Python', 'is', 'nice')

Notice that Python exceptions used to be strings on ancient times, and string
exceptions are still allowed for backward compatibility reasons. The expr
function won't work right with those. 

You can also play with traceback objects! :)

>>> import traceback, sys
>>> def more_fun(f):
        try:
                f()
        except:
                cls, inst, tb = sys.exc_info()
                print "Exception class:", cls
                print "Exeption instance:", inst
                return tb

	
>>> tb = more_fun(z)
Exception class: exceptions.ZeroDivisionError
Exeption instance: integer division or modulo by zero
>>> traceback.print_tb(tb)
  File "<pyshell#159>", line 3, in more_fun
    f()
  File "<pyshell#101>", line 2, in z
    1/0

More info in the Library manual, chapters for modules "sys" and "traceback".

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus at thinkware.se



More information about the Tutor mailing list