Menu

Post image 1
Post image 2
1 / 2
0

Use exceptions for (wait for it) exceptional things

DEV Community·Ian Johnson·19 days ago
#FxpbFaHp
Reading 0:00
15s threshold

You know the code. A function tries to do something, something goes wrong, and you see: print ( f " Error: could not load config from { path } " ) sys . exit ( 1 ) Enter fullscreen mode Exit fullscreen mode Or this: result = fetch_user ( user_id ) if result is None : return None profile = fetch_profile ( result . id ) if profile is None : return None ... Enter fullscreen mode Exit fullscreen mode Or, in a slightly more sophisticated codebase, the function returns a tuple of (value, error) or a dict like {"ok": False, "error": "..."} and every caller has to remember to check it. What these patterns share is that they're working hard to avoid using the feature the language built specifically for this situation: exceptions. The avoidance is real I don't have data, just years of reading other people's code. But the pattern is consistent: a lot of developers will reach for almost anything before raising an exception. They'll print and continue. They'll die or os.exit .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More