Created
November 5, 2019 09:13
-
-
Save kjk/646f2e936bff82f90b7fbc62f891bf3c to your computer and use it in GitHub Desktop.
Error handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// :collection Essential Go | |
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
// :show start | |
func sqrt(n float64) (float64, error) { | |
if n < 0 { | |
return 0, fmt.Errorf("invalid argument '%f', must be >= 0", n) | |
} | |
return math.Sqrt(n), nil | |
} | |
func printSqrt(n float64) { | |
if res, err := sqrt(n); err == nil { | |
fmt.Printf("sqrt of %f is %f\n", n, res) | |
} else { | |
fmt.Printf("sqrt of %f returned error '%s'\n", n, err) | |
} | |
} | |
func main() { | |
printSqrt(16) | |
printSqrt(-16) | |
} | |
// :show end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment