Chapter 3 - Functions
Exercise 3: Error Handling
Update your perimeter
function from the previous exercise to return an error if either the length or width are negative.
- If the given length is negative, return a perimeter of
0
and an error with the message “a length of [length] is invalid”. - If the given width is negative, return a perimeter of
0
and an error with the message “a width of [width] is invalid”. - Otherwise, return the calculated perimeter, and an error value of
nil
.
In your main
function, test returning an error by calling perimeter
with a negative value. If the returned error value is not nil
, print the error message and exit the program. Otherwise, print the returned perimeter.
Solution
Output:
2019/05/25 15:06:35 a width of -10.00 is invalid
exit status 1