Boss lesson · Unit 03
When it goes wrong
A bad row in a payments file, from silence to a useful report
What you practise
- Exceptions against returned errors, failing early and loudly, the swallowed exception, validating at the edges, missing values handled once
Try a question from this lesson
Pick one
A lookup by email finds no user. A required settings file is missing when the program starts. Which pair of reactions fits?
Hint
Which of the two is an ordinary outcome that the caller expects and can handle?
Correct answer
Return "no such user"; stop at start-up for the file
Why
A missing user is an expected outcome: say so in the return value and let the caller decide. A missing required file is a broken assumption: the program cannot do its job, and stopping with a clear message beats limping on with empty settings.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Fail early, fail loudly
When input is wrong, stop at the first spot where you can tell, and say what was wrong.
An error raised at the door names the bad value. A quiet default travels on and surfaces later as a wrong total, far away from its cause.
def parse(text):
if not text.isdigit():
message = "bad amount: " + text
raise ValueError(message)
return int(text)function parse(text) {
if (!/^[0-9]+$/.test(text)) {
const message = "bad amount: " + text;
throw new Error(message);
}
return Number(text);
}function parse(text: string): number {
if (!/^[0-9]+$/.test(text)) {
const message = "bad amount: " + text;
throw new Error(message);
}
return Number(text);
}TypeScript note/^[0-9]+$/ is a pattern for "one or more digits and nothing else". Its test method answers true or false for a string.
10 more exercises in the app
- 4× type the answer
- 1× fill the blanks
- 2× multiple choice
- 1× true or false
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.