Calling a user-defined Exception from within a function. Need Help.

D-Man dsh8290 at rit.edu
Tue Jul 3 19:18:40 CEST 2001


On Tue, Jul 03, 2001 at 02:54:47PM +0000, jestes39 at yahoo.com wrote:
| I am still learning Python basics. I am trying to raise exceptions 
| within a function. The problem is that my named exceptions aren't 
| being recognized. They were working before I split the code up into 
| modules. I just need to know where I need to define the exceptions or 
| if I have to do something special to get them to work. Here's the 
| basic shell of the code:
| 
|   import sys
|   import telnetlib
|   import dbi,odbc
|   import exceptions
| 
|   class database_error(exceptions.Exception):
...
|   class other(exceptions.Exception):
...
|   def parse(record):
|       try:
|           #Parse the row into the variables that will be used to 
|           #  populate the receiving fields
|           .....
|           .....
|           return 'TRUE'
|       except:
|           return 'FALSE'

IMO it is better to raise an exception than to catch all of them and
return a boolean.  This is Python, not C, after all :-).

|   def receipt(record):
...
|               if parse(record) == 'FALSE':
For example, here, you could just let the exception from 'parse'
propagate upwards, rather than checking the return value and then
raising a new exception.

|                   raise other

I think this line is wrong, but I could be wrong.  Can classes be
raised, or just instances?  I think you mean to raise an instance
anyways so change it to 

                    raise other()

|       except database_error:
|           dbc = None
|           crsr = None
|           tn.close()
|           print 'we made it to the database exception'
|       except other:
|           dbc = None
|           crsr = None
|           tn.close()    
|           print 'unidentified error'
|       except:
|           dbc = None
|           crsr = None
|           tn.close()
|           print 'unhandled exception'

The first 2 except clauses can be simplified down to :

    except (database_error , other ) err :
        dbc = None
        crsr = None
        tn.close()
        print err   # let the exception itself define what a useful
                    # message will be

The only difference here is that unexpected exceptions are caught
(such as SystemExit, as Steve mentioned).

Alternatively, if you want the error (exception) to propagate upwards,
you can use a 'finally' clause :

    finally :
        dbc = None
        crsr = None
        tn.close()
        print sys.exc_info()  # this gives you access to the
                              # exception, but check the spelling as
                              # I'm not 100% certain

Which one you should use depends on the exact semantics you want in
your program.

-D





More information about the Python-list mailing list