Help req: Problems with MySQLdb

Bruno Desthuilliers onurb at xiludom.gro
Thu Jun 22 12:10:43 CEST 2006


rodmc wrote:
(top-post corrected)
> Sybren Stuvel wrote:
> 
>>rodmc enlightened us with:
>>
>>>--- it refuses to connect on the above line and the exception is
>>>caught and a message displayed.
>>
>>So.... why do you think this exception and the error message contain
>>no useful information at all?


> Hi,
>
> Thanks for your email. Well I am kind of new to exceptions in Python,
> but here is the code used below, as you can see it is somewhat basic.
> Is there a way to display more information about the exception?

Yes : don't catch it. You'll then have all the needed infos.

If you want to catch it so you can do some logging, issue a more
user-friendly error message etc, then do something like this:

try:
  SomethingThatMayRaise()
except ClassOfExceptedException, e:
  # e is the exception, let you access error message, traceback etc
  doSomethingWithException(e)


Some general rules about exception handling:
- *don't* use bare except clause. Never. Well, almost never (cf below)
- if you can't fix the problem, just let the exception propagate
- at the top level of the main program, have a catch-almost-all
exception handler, that will do logging if possible, proper error
reporting if possible, sanity clean-up if possible, and then crash as
noisily as possible.

>
> try:  #Exception handler for database queries
>             db = MySQLdb.connect(host=DBSERVERIP, user="user",
> passwd="password", db="nuke")
>  except:
>             print "A database connection error has occurred"
>             return False

This is the most useless and worst possible way to handle exceptions.
Just get rid of this exception handler - letting the program crash with
full traceback would be much much better - at least you'd have a chance
to get some usefull informations about what went wrong.


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list