×

python · level 3 · unit 7 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.