blanket except clause -- best practice?

George Young gry at ll.mit.edu
Tue Oct 28 12:21:54 EST 2003


[python 2.3.2, SuSE Linux 8.2, x86]
I have a bunch of blanket "except:" clauses like:
[OK, it's not "my" code but I use it and it troubles me...]

class DatabaseError(StandardError): pass
class OperationalError(StandardError): pass

try:
	stuff
except _pg.error, msg:
	raise DatabaseError, "error '%s' in '%s'" % ( msg, sql )
except:
        raise OperationalError, "internal error in '%s'" % sql


This accomplishes passing useful info, namely "sql", on with
the exception.  Unfortunately it *loses* info in that upstream
has no way to know *which* exception triggered this or what args
it might have been given.  I'm trying to think of a clean way
to improve this.  I could do:

try:
	stuff
except _pg.error, msg:
	raise DatabaseError, "error '%s' in '%s'" % ( msg, sql )
except Exception, x:
	raise OperationalError, "internal %s(%s) error in '%s'" (x.__class__,
x.args, sql)


Is there something more clear/portable/pythonic than this?
How do people handle this sort of fallback "except" clause?

-- George




More information about the Python-list mailing list