Loading
0x60Lesson 7 of 9

Handle errors and validate input

Use explicit error checks to keep Go programs reliable.

14 min 4-question quiz 1 code exercise
By the end of this lesson you can
  • Parse and validate input using Go’s explicit error handling style.

Go uses explicit error values instead of exceptions for most recoverable failures. Functions often return (value, error), and callers check if err != nil immediately. This makes failure paths visible and keeps behavior predictable in scripts and services.

main.go
1package main
2
3import (
4    "fmt"
5    "strconv"
6)
7
8func main() {
9    text := "42"
10    value, err := strconv.Atoi(text)
11    if err != nil {
12        fmt.Println("invalid")
13        return
14    }
15    fmt.Println(value * 2)
16}
Output
84

When input can be imperfect, parse each value and decide how to handle failures (skip, fallback, or stop). Small clear checks near each operation are easier to maintain than one large failure handler.

Key takeaways

  • Parse and validate input using Go’s explicit error handling style.

  • Go catches many mistakes while compiling.

  • Use small experiments to understand each new language feature.

Lesson quiz

4 questions · pass with 3 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Go

Write Go in the editor and run it against sample input with a remote compiler. Your code is sent to Compiler Explorer to compile and run.

Exercise 1

Sum only valid integers

+25 XP

Read a count followed by that many tokens. Parse each token with strconv.Atoi; add only valid integers and print the total.

  • Mixed tokens
  • All invalid
main.go
Loading editor…

Go is compiled and run by Compiler Explorer (godbolt.org), a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…