[Tutor] Try/Except, A better way?

Jeff Shannon jeff@ccvcorp.com
Fri Mar 21 18:32:01 2003


Lucid Drake wrote:

>I currently use a few Try/Except clauses in my programming and was
>hoping to find a better way to do certain things.
>
>For instance, if I need to check if someone is in a database, I run a
>select statement asking for her, if she is there I update,
>if she isn't there, I insert.
>
>Like so...
>
>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?
>
>How appropriate is this type of coding?
>

Yes, it should be a simple matter of declaring the error types.  You can 
even have different responses to different exceptions:

try:
    [...]
except NotFoundError:
    [....]
except DatabaseAccessError:
    [....]

This is perfectly appropriate coding, providing that your code throws 
appropriate exceptions.  One of the Python mantras is "It's easier to 
ask forgiveness than permission" -- that's exactly what you're doing 
here.  Just remember, when you're catching exceptions, to be as specific 
as possible so that you're not catching unexpected exceptions with code 
that's designed to handle only a specific type of error.

(I agree with the other respondent that the speed of try/except vs. 
if/else is very unlikely to be a significant consideration, but I think 
that a properly specific try/except is a very good way of handling this 
sort of situation.)

Jeff Shannon
Technician/Programmer
Credit International