Add words discouraging overly-broad except clauses.

This commit is contained in:
Guido van Rossum 2007-04-06 15:09:21 +00:00
parent 799cd54779
commit 38fbef2fb2
1 changed files with 22 additions and 0 deletions

View File

@ -689,6 +689,28 @@ Programming Recommendations
the exception propagate upwards with 'raise'.
'try...finally' is a better way to handle this case.
- Additionally, for all try/except clauses, limit the 'try' clause
to the absolute minimum amount of code necessary. Again, this
avoids masking bugs.
Yes:
try:
value = collection[key]
except KeyError:
return key_not_found(key)
else:
return handle_value(value)
No:
try:
# Too broad!
return handle_value(collection[key])
except KeyError:
# Will also catch KeyError raised by handle_value()
return key_not_found(key)
- Use string methods instead of the string module.
String methods are always much faster and share the same API with