This is not unique to Python. Other answers are good, but only some additional thoughts that did not fit into the comment:
- You use exceptions if you do not want (or need) to check the result. In this mode, you just do it, and if there is an error somewhere, you make an exception. Getting rid of explicit checks makes shorter code, and you still get good debugging information when you get an exception, so it's common. This is the EAFP style described above (easier to ask than permission).
- You use return codes when you want to check the result. Explicit verification is sometimes necessary if failures do not always fail or help debug complex code streams. This is sometimes called the LBYL style (look before you jump).
In Python, like most interpreted languages, since the overhead is so high, exceptions are relatively cheap, so it's much wider to use EAFP in Python than, say, C ++, where overhead is lower and exceptions are (relatively) more expensive.
Note that a function may give a return value and may possibly throw an exception.
In your example, a function like doesPointExist implies that the user really wants to check access before trying something. This is LBYL. Throwing an exception as the result value is part of the EAFP programming style and does not make sense for this function - if you want this style, you will not check it, you just do it and catch the exception when the point does not exist.
However, even here there are assumptions - that you gave a valid point. It would be nice if the function returns True / False for whether a point exists, throwing an exception if something that was not a point was passed to it.
source share