Go from Zero 09. Errors Example

Safe Calculator

Handle division by zero and bad input with proper error checking.

package main

import (
	"fmt"
	"strconv"
)

func parseNumber(s string) (float64, error) {
	n, err := strconv.ParseFloat(s, 64)
	if err != nil {
		return 0, fmt.Errorf("'%s' is not a valid number", s)
	}
	return n, nil
}

func divide(a, b float64) (float64, error) {
	if b == 0 {
		return 0, fmt.Errorf("cannot divide by zero")
	}
	return a / b, nil
}

func main() {
	inputs := [][]string{
		{"10", "3"},
		{"20", "4"},
		{"10", "0"},
		{"10", "abc"},
	}

	for _, pair := range inputs {
		a, err := parseNumber(pair[0])
		if err != nil {
			fmt.Println("Error:", err)
			continue
		}

		b, err := parseNumber(pair[1])
		if err != nil {
			fmt.Println("Error:", err)
			continue
		}

		result, err := divide(a, b)
		if err != nil {
			fmt.Println("Error:", err)
			continue
		}

		fmt.Printf("%s / %s = %.2f\n", pair[0], pair[1], result)
	}
	// 10 / 3 = 3.33
	// 20 / 4 = 5.00
	// Error: cannot divide by zero
	// Error: 'abc' is not a valid number
}
▶ Open Go Playground

Copy the code above and paste to run

© 2026 ByteLearn.dev. Free courses for developers. · Privacy