[Tutor] Try/Except, A better way?

Michael Janssen Janssen@rz.uni-frankfurt.de
Fri Mar 21 18:47:01 2003


On Tue, 18 Mar 2003, Lucid Drake wrote:
> try:
>     # select * from user where id = <num>
>
>     # update user set ... where id = <num>
>
> except:
>     # insert into user ...
>
> I've noticed that the try/except clauses cause me problems later on
> when I'm changing code around and debugging by not logging the errors.
>
> Is this a simple matter of declaring the error types in the except
> clauses, instead of catching all errors?

strongly recommended. For best result with "try/except" strategie you
should narrow the try-statements to smallest necessary: otherwise you
might catch an exception that was raised by a part of the code, you
doesn't thought of, even if you give an error type.

I don't know if database-queries provide a finegraded set of error types.
Therefore you probably should avoid "trying" two queries in one step. But
I can't determine the reason, why you have first to "select" and than to
"update".

> How appropriate is this type of coding?
>
> Would it be more appropriate to query for the user and use an
> if/else statement? (i don't do this now because it's slower)

Both approaches are valuable. Since try/except could send you into hard to
debug "wrong-error-caught-bugs", if/else might be your first try. But
sometimes it's "Easier to Ask Forgivenes than Permission": In case the
check that next operation is allowed costs time or many typing or
readability try/except comes in handy. Also, in many cases it's very easy
to make shure, that the try statement(s) can only throw a distinct error.

If/else, on the other hand, can be insufficient in some/ many situations.
It depends on the details of your code, what's best.

Python Cookbook recipe 5.3 tells (a bit) more.

On a sidenote: It's not best to choose the algorithem first by runtime
than by how stable or just readable it is. Better the other way round: In
case you got two stable implementations you can choose by runtime
(optimizing runtime against maturity is worth only for throw-away
skripts; the programmer always in sight ;-).

Michael

>
> Thanks,
> --Lucid
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>