Handle errors and validate input
Use explicit error checks to keep Go programs reliable.
- 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.
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}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.
Sum only valid integers
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
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…