python · level 3 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Catch expected errors at the top and explain them kindly.
A tool should never answer a user's mistake, like a missing file or a bad option, with a traceback. Catch those expected errors once, in main, and print one clear sentence saying what went wrong and how to fix it.
Send that message to with print(..., file=sys.stderr), keeping for real results. Then return an : 0 for success, 1 or more for failure, so other programs can tell what happened.
Catch only the errors you expect. A real bug should still crash loudly, so you find it.
import sys
def main(argv):
try:
rate = float(argv[0])
except (ValueError, IndexError):
print("convert: give a rate like 1.17", file=sys.stderr)
return 1
print(f"100 GBP is {100 * rate:.2f} EUR")
return 0
print("exit code", main(["1.17"]))
print("exit code", main(["lots"]))
print("exit code", main([])) A real program ends with sys.exit(main(sys.argv[1:])), which hands the exit code to whatever started it.
guess first
Someone types a word, not a number. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import sys
def main(argv):
try:
count = int(argv[0])
except ValueError:
print("error: count must be a number", file=sys.stderr)
return 2
print("ok", count)
return 0
status = main(["ten"])
print("finished with", status)
your turn
Your turn. Make a tool fail politely.
Write a helpful message in the first blank, send it to the error stream in the second, and return a failure exit code in the third.
fix it
The prices are fine, but the tool blames them.
- Both prices are whole numbers, yet the tool complains. Is its message telling the truth?
except Exceptioncatches every error, even the typo on line 6, and blames the prices for it.- Change
totltototal, and catch onlyValueErrorso real bugs still crash, then run.
nailed it
your tool fails like a professional. :D
- Catch expected errors in
mainand explain them in one sentence. - Problems go to
sys.stderr, with a non-zero exit code. - Catch only what you expect, so real bugs still crash.
new words in your collection
- stdout
- stderr
- exit code
This lesson isn’t saved. A free account remembers every lesson you finish.