On 11/04/20 2:34 am, Chris Angelico wrote:
AttributeError, KeyError/IndexError, and GeneratorExit (and StopAsyncIteration) want to say hi too.
Okay, there are a few others. But the important thing for our purposes is that APIs designed specifically to use exceptions for flow control (such as StopIteration and GeneratorExit) define their own special exceptions for the purpose. Nothing else raises them, so it's usually fairly safe to catch them.
On the other hand, I don't really think of AttributeError, KeyError or IndexError as exceptions intended primarily for flow control. To my mind they're in the same category as TypeError and ValueError -- they signal that you tried to do something that can't be done.
While you *can* use them for flow control, you need to be careful how you go about it. And there is usually another way to get the same result that doesn't require catching an exception, e.g, dict.get().
The only one of these that can be a bit of a problem is AttributeError, because there is no other way to attempt to get an attribute that may or may not be there (even hasattr() calls getattr() under the covers and catches AttributeError).
Anyway, I'm not denying that there are sometimes problems in this area. But I'm not convinced they're so rampant and widespread that we need a whole new language mechanism to deal with them.