Errors With Names
Stardate 55146.1 ยท UES Magnanimous
Briefing
Since the heading validator went in, the helm has been refusing bad input, which is correct, and reporting every refusal as "something went wrong", which is not. Ensign Tannenbaum typed "north" and 720 and got the same message for both, and has pointed out, not unreasonably, that he cannot learn from that.
Chief T'Kala wants errors with names. Not a number: an out-of-range heading. Two different failures, two different errors, each carrying the thing that was wrong with it, so the message can say "720 is not a heading" and mean it. In Python that is your own exception class. In Rust it is an enum, and the compiler will make sure every caller handles both.
Mission objectives
ARCHIE checks all five every time you run diagnostics.
- โขA valid heading is accepted and returned as a number
- โขText that is not a number raises the named error, carrying the text
- โขA number out of range raises the named error, carrying the number
- โขThe error is a specific type, distinguishable from any other failure
- โขWhitespace around a valid heading is fine
Objective
Define class HeadingError(ValueError). Write
set_heading(text): return the heading as an int if
text is a whole number 0 to 359 (whitespace allowed). Otherwise raise
HeadingError whose message contains the offending text or number, for
example "north is not a number" or "720 is out of range".
Press Run Diagnostics and I will tell you which objectives you actually met.
Objective
Keep the enum as given. Write set_heading(text: &str) -> Result<u16,
HeadingError>: Ok(heading) if text is a whole number
0 to 359 (whitespace allowed); Err(HeadingError::NotANumber(text)) if it
does not parse as an integer; Err(HeadingError::OutOfRange(n)) if it
parses but is outside 0 to 359.
Press Run Diagnostics and I will tell you which objectives you actually met.
Ask Commander Raghunathan for a hint
Python: define class HeadingError(ValueError), and raise it with a message that includes the offending value. Rust: an enum with two variants holding data, NotANumber(String) and OutOfRange(i64), returned in Err.
Debrief
"north is not a number." "720 is out of range." Ensign Tannenbaum has read both messages and understood both messages, and has typed 180, which worked. Chief T'Kala has made a small note in her list and moved on to item two.