3 ms·
Not only is it overly-verbose and ultimately unnecessary (as shown by the alternative that follows in the article) but this mechanism is actually broken. For i
by makecheck 14y ago
Not only is it overly-verbose and ultimately unnecessary (as shown by the alternative that follows in the article) but this mechanism is actually broken. For instance if "freqs" were data given to you from somewhere else and "freqs[c]" happened to have a type that cannot legally have 1 added to it, you'd want to see this error. The "except:" however will absorb any and all exception types and respond to all of them by setting the value to 1.
- Estragon 14y agoAlso, raising exceptions used to be quite slow, which could hurt for a sparse counting set. Don't know whether that's still the case.
- underwater 14y agoAlso Exceptions should be used in "exceptional" circumstances and not as part of normal flow.
- koenigdavidmj 14y agoOne exception (teehee!) to the rule: file operations and other things where atomicity matters. Example code: if not os.path.exists("foo"): os.mkdir("foo") That introduces a race condition. If foo does not exist on the first line but is created by something else on the second line then this will raise an exception. The proper code is: import errno try: os.mkdir("foo") except OSError as exc: if exc.errno != errno.EEXIST: raise That doesn't have the race condition. (Yes, that's wordy. Eventually they plan to add to Python 3 a fancier exception hierarchy described at http://www.python.org/dev/peps/pep-3151/ http://www.python.org/dev/peps/pep-3151/ , which lets you filter at a more fine-grained level, as below.) try: os.mkdir("foo") except FileExistsError: pass
- makecheck 14y agoIt's good to point out the race condition. To solve this particular problem in future code more compactly however, note that Python 3.2 (finally) adds an "exist_ok" Boolean keyword parameter to the multi-directory variant, os.makedirs(). In other words, calling os.makedirs("mydir", exist_ok=True) will silently ignore existing directories and only raise if other errors occur.
- GrumpySimon 14y agoThank you for pointing that out, I've just changed some code :)