On 22/05/13 15:46, Jim Mooney wrote:
I'm looking at Try..Except

Try:
      <some statements>
Except SomethingError as err:
     <other statements>

The list of error statements is huge. How do I know which error
statement to put in place of SomethingError (or multiple errors for
that matter)? Or is it best to just leave SomethingError blank until I
know more?



For playing around at the interactive interpreter, leaving the except clause 
blank is fine.

try:
    something()
except:
    pass


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;

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;

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*.



Unfortunately there is no hard rule about what exceptions Python will raise. 
Some things are obvious: if you mistype a name, you'll probably get a 
NameError. Some things are documented: if you look up an item in a dict, and it 
is not there, you will get KeyError. Some things are not. E.g. there's pretty 
much no limit to the exceptions you *might* (but probably never will!) get from 
some of the more complex modules.

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.



--
Steven
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to