[Tutor] try..except - what about that ton of **Error statements?

boB Stepp robertvstepp at gmail.com
Wed May 22 15:31:08 CEST 2013


On Wed, May 22, 2013 at 7:50 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 22/05/13 15:46, Jim Mooney wrote:
>>

[...]

>
> But don't do this in real code! In real code, the rules you should apply
> are:
>
>
> 1) never hide programming errors by catching exceptions;
>
> 2) errors should only be caught if you can recover from them;
>

I have not made it to the point of catching errors. I am still at the
stage of doing my best to prevent them from occurring. However, I try
to follow all of the posts as best I can and I am not sure I
understand what you mean here. You seem to be saying that there may be
errors that you cannot eliminate, but also cannot do anything about if
they happen to occur. Am I interpreting this correctly? Please
clarify.

> 3) your job as a programmer is *not* to stop your program from raising an
> error, but to make it behave correctly -- sometimes an error is the right
> thing to do;
>

Also, can you clarify this point as well? When would you want your
program to crash?

> 4) catch the fewest possible errors that make sense;
>
> 5) nearly always, "the fewest" will mean *zero* -- 99% of your code should
> not be inside a try...except block;
>
> 6) you should put the least amount of code as possible inside each try block
> -- as a general rule, that doesn't just mean "one line of code", but *one
> operation*.
>

Here by "one operation" do you mean the most efficient means to deal
with that particular error condition?

[...]

> In general, once I have decided that I need a try...except block around a
> certain operation, I look up what exceptions it is documented to produce (if
> any!). Then I decide, if such-and-such an exception occurs, can I recover
> from it? If not, I don't catch it. If so, then I do. Then, I wait to see if
> the operation produces some other undocumented exception. If so, then I
> repeat the process.
>
Maybe I have been totally misunderstanding your comments. Is what you
are saying above referring strictly to while you are still debugging
the program? Or do the above comments that I asked for clarification
refer to the finished product?

Thanks!
boB


More information about the Tutor mailing list