I\'m working with Python and whenever I\'ve had to validate function input, I assumed that the input worked, and then caught errors.
In my case, I had a universal
I upvoted Matt Joiner's answer, but wanted to include some additional observations to make it clear that, along with a couple of other factors, there are 4 times that matter when choosing between pre-checking conditions (known as LBYL or "Look Before You Leap") and just handling exceptions (known as EAFP or "Easier to Ask Forgiveness than Permission").
Those timings are:
The additional factors are:
That last point is the one that needs to be addressed first: if there is a potential for a race condition, then you have no choice, you must use exception handling. A classic example is:
if <dir does not exist>:
<create dir> # May still fail if another process creates the target dir
Since LBYL doesn't rule out the exception is such cases, it offers no real benefit and there's no judgement call to be made: EAFP is the only approach that will handle the race condition correctly.
But if there's no race condition, either approach is potentially viable. They offer different trade-offs:
That then leads to the following decision criteria:
As a rough rule of thumb:
*People will vary as to what they consider "most of the time" in this context. For me, if I expect the operation to succeed more than half the time, I would just use EAFP as a matter of course, until I had reason to suspect this piece of code was an actual performance bottleneck.
In Python, exceptions are often faster due to the reduced number of lookups. However a friend once said (and it should apply to any language), pretend that everytime an exception is caught, there is a small delay. Avoid using exceptions where a delay could be a problem.
In the example you've given, I'd go with the exception.