Error Handling

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Apr 21 00:02:56 EDT 2008


En Thu, 17 Apr 2008 16:19:12 -0300, Victor Subervi <victorsubervi at gmail.com> escribió:

>     try:
>       cursor.execute(sql)
>       print '¡Exito en introducir!<br />'
>       print '<i>Esta página va a regresar a la página principal del carrito
> de compras en 10 segundos.</i>'
>     except IntegrityError:
>       print 'Lo siento, pero el ID que entraste está usado actualmente por
> otra entrada. Favor de dar para atráz y escojer otro número.'
>     except OperationalError:
>       print 'Lo siento, pero has añadido un carácter extraño a un número (o
> en "ID", "precio", "recámaras" o "baños". Favor de dar para atráz y escojer
> otro número.'
>     except:
>       print 'Lo siento, pero hay un error. Favor de dar para atráz y
> averiguar donde está el error, y reintentar.'
> When I enter and ID that is not a number, it should trigger the
> IntegrityError. Instead, I get this in the error log:
>
> [Thu Apr 17 12:06:37 2008] [error] [client 190.166.0.245] PythonHandler
> mod_python.cgihandler: NameError: global name 'IntegrityError' is not
> defined, referer: http://livestocksling.com/bre/iud.py

Looks like IntegrityError and OperationalError are defined inside your database module. Either use:

   from my_database_module import IntegrityError, OperationalError

   try
       ...
   except OperationalError: ...
   except IntegrityError: ...
   except Exception: ...

or else:

   import my_database_module

   try
       ...
   except my_database_module.OperationalError: ...
   except my_database_module.IntegrityError: ...
   except Exception: ...

It's the same as any other symbol, like math.sqrt or os.rename

Note that I've not used a bare except: clause; it's not a good idea. sys.exit() raises the SystemExit exception, and pressing Ctrl-C raises KeyboardInterrupt; a bare except: will catch them, effectively nullifying the intended purpose.

-- 
Gabriel Genellina




More information about the Python-list mailing list