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
package main
import (
"fmt"
"log"
)
func perimeter(length float64, width float64) (float64, error) {
if length < 0 {
return 0, fmt.Errorf("a length of %0.2f is invalid", length)
}
if width < 0 {
return 0, fmt.Errorf("a width of %0.2f is invalid", width)
}
return length*2 + width*2, nil
}
func main() {
p, err := perimeter(8.2, -10)
if err != nil {
log.Fatal(err)
}
fmt.Println(p)
}
Output:
2019/05/25 15:06:35 a width of -10.00 is invalid
exit status 1