vizcayno wrote: > Hello: > Need your help in the "correct" definition of the next function. If > necessary, I would like to know about a web site or documentation that > tells me about best practices in defining functions, especially for > those that consider the error exceptions management. > I have the next alternatives but I think there are better: > > Alternative 1: > ============= > def ExecuteSQL(cmdSQL, cursor): > try: > cursor.execute(cmdSQL) > except Exception, e: > return e > return 1 > > Seems a good solution but the function is not returning an uniform > type, should the code that receives the function result decides the > error display according of datatype? If I do this in C# I think I will > have problems. > > > Alternative 2: > ============= > def ExecuteSQL(cmdSQL, cursor): > try: > cursor.execute(cmdSQL) > except Exception, e: > return 0, e # or return (0,e.message) > return 1, "ok" # or return (1, "ok") > Sounds good, but seems forced. When doing return 1, "ok" I am doing > redundancy and I have problems with the type (e is exception type and > "ok" is string). > > > Alternative 3: > ============= > def ExecuteSQL(cmdSQL, cursor): > try: > cursor.execute(cmdSQL) > except Exception, e: > print "ERROR:", e > return 0 > return 1 > > It solves the problem of alternative 1 and 2, but the print keyword > would have problems if the function is called from an WEB or GUI > application and, because there are plans to convert print into a > function in py3k. > > > Alternative 4: > ============= > def ExecuteSQL(cmdSQL, cursor): > try: > cursor.execute(cmdSQL) > except Exception, e: > print >> logerr, e.message > return 0 > return 1 > > Seems a good solution but I should always be persuaded to have an open > global file (logerr) when invoking this function; otherwise code will > generate another error. The function is not totally independent.I think > I would be in the same situation when using the "logging" battery. > > Thanks for your attention. > > Regards,
My vote goes to None Of The Above. In neither alternative you actually do anything useful with the exception other than reporting it in some ad-hoc way. If that's all you can and/or want to do with it (i.e. no error recovery of some sort), the typical thing to do is nothing; just let it propagate up the call stack until the appropriate level. This might be the console, a GUI, a logfile, an automatically sent email or any combination of these or more. If it's a programmer's error (aka bug), it should propagate all the way up and end in printing the stack trace. The bottom line is, it's simply not this function's (ExecuteSQL) job to deal with the error, so it shouldn't. Most important, returning an error or status code is rarely (if ever) desirable or necessary in Python; that's what exceptions are for. George -- http://mail.python.org/mailman/listinfo/python-list