Add words discouraging overly-broad except clauses.
This commit is contained in:
parent
799cd54779
commit
38fbef2fb2
22
pep-0008.txt
22
pep-0008.txt
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue