Go · Stage 8 – Errors and Files · Lesson 47 of 64

The if err != nil Pattern

Handle a returned error immediately and clearly.

Go code

number, err := strconv.Atoi("no")
if err != nil {
    fmt.Println("Invalid number")
    return
}
fmt.Println(number)
Line-by-line explanation
  1. Atoi cannot convert no.
  2. The if detects a non-nil error.
  3. A helpful message is displayed.
  4. Return stops the current function.
Expected output
Invalid number

This is the expected result.