[FRPythoneers] trapping exceptions

Mike Romberg romberg at fsl.noaa.gov
Wed May 21 11:57:21 MDT 2003


>>>>> " " == Jim Vickroy <Jim.Vickroy at noaa.gov> writes:

     > Erick, As I see it, the problem is that in order for your
     > "except" block to work, a "MyException" must be raised.  If its
     > your code raising the exception, then you can obviously raise a
     > "MyException" and it would work as you intend.  But standard,
     > distribution Python code raises IOError exceptions which your
     > except block does not handle.

     > In general, I do not see how you can do anything but the
     > following:

[snip]

  Well, you are right in that you probably want to do something like
you describe.  But the cool thing about python is that the guts are
accessible.  So, you could do a trick like this:

class MyException(EnvironmentError):
    def __init__(self):
        # You will want to make sure that this
        # class ctor does at least the same thing
        # as EnvironmentError (takes same arguments
        # etc.
        pass

# Now we simply rearrange the exception inheritance tree
# to put our new Exception in between EnvironmentError and
# IOError
IOError.__bases__ = (MyException,)

# And now this should work

try:
    f = open('doesnotexist.txt')
except MyException, e:
    print "caught MyException: ", e


  But like I say, I'm not sure you really want to do this.  Python
allows alot of ways to modify code on the fly.  But I'm not sure it is
the best solution.  It is still kinda a neat trick though :).

Mike Romberg (romberg at fsl.noaa.gov)



More information about the FRPythoneers mailing list