← All lessons

Mini project: a safe calculator

Sign in · Sign up

Lesson 8.7

Let's bring everything from the module into one calculator that never crashes and keeps a log.

Your own errors: CalcError for bad numbers and BadAgeError for a bad age. Both classes inherit from Exception.

The functions:

  • safe_div(a, b) — returns int(a) / int(b), the result is float (for example, 3.0); if a or b is not a number, raises CalcError("Numbers are needed"); if b is zero, raises CalcError("Division by zero");
  • check_age(age) — returns int(age) if the age is from 0 to 150; not a number — don't catch the ValueError from int(); out of range — BadAgeError with the message Age out of range: <age>.

The program divides a by b and checks age. Each call is in its own try/except/else/finally:

block what to do
except print Error: <message> and record logging.error(<message>)
else print the result and record logging.info(...)
finally print Done

In the calculator block catch CalcError — all the division trouble is already in it. In the age block catch ValueError and BadAgeError separately: that way you can see exactly which error happened.

Let assert check a your own assumption: for example, that safe_div can be called. That's how it is done in tests, while user data is checked with try/except.

At the start wipe calc.log with logbook.reset, and at the end print its records without the date — with logbook.read and logbook.without_time, as in the previous lesson.

Hint

First the error classes (no double underscores needed — ordinary names), then the two functions, then the two try blocks.

In try — the call and the assignment, the printing and the log go in else, Done goes in finally. One block catches both ValueError and your own error. At the end — logbook.read and the output without the date.