Member-only story
#3 Error Code VS Exception
During code review. there is some error handling mistakes that keep happening again and again.
Just to share what they are, and why I think they are “anti-patterns”.
Let’s start
#1 Use exceptions to handle logic errors
So how many times have you seen the below code?
def get_user_by_id(id): # e.g. id: X_1234, Y_2345
try :
id = int (id[2:])
except ValueError, IndexError:
raise UnexpectedInput(id)
or this
def save_billing(bill):
try:
paied_by = bill["user_id"]
paied_user = get_user_by_id(paied_by) # could be none here
first_order_item = bill["order"][0]
...
except (IndexError, ValueError, KeyError ...):
raise UnexpectedInput(bill)
Normally It’s fine to leave the null check or index check to try-catch block, and I agree the above code will work.
There may not be much difference when the exception only happens in 1 out of 1000 calls in some system RPS < 100.
But what if it’s a public-facing internet company? let’s say Amazon or Facebook, there are millions of orders (or tweets) per second. and what’s the cost when using exceptions to handle logic errors? Slow. slow means less throughput which means losing money, potentially.