0
0
GoDebug / FixBeginner · 3 min read

How to Handle Errors in Go: Simple and Effective Techniques

In Go, errors are handled by returning a value of type error from functions and checking it explicitly. Use if err != nil to detect and handle errors gracefully, ensuring your program can respond properly to unexpected situations.
🔍

Why This Happens

In Go, functions often return an error value to indicate something went wrong. If you ignore this error, your program might continue with wrong data or crash unexpectedly. This happens because Go does not use exceptions like some other languages; it expects you to check errors explicitly.

go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	// Ignoring error returned by strconv.Atoi
	number, _ := strconv.Atoi("abc")
	fmt.Println("Number is", number)
}
Output
Number is 0
🔧

The Fix

Always check the error returned by functions. Use if err != nil to detect errors and handle them properly, such as printing a message or stopping execution. This makes your program safer and easier to debug.

go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	number, err := strconv.Atoi("abc")
	if err != nil {
		fmt.Println("Error converting string to number:", err)
		return
	}
	fmt.Println("Number is", number)
}
Output
Error converting string to number: strconv.Atoi: parsing "abc": invalid syntax
🛡️

Prevention

To avoid error handling mistakes, always check errors immediately after calling functions that return them. Use clear error messages and consider wrapping errors for more context. Tools like golangci-lint can help catch ignored errors during development. Writing small functions that return errors makes your code easier to test and maintain.

⚠️

Related Errors

Common related errors include:

  • Ignoring errors from file operations, causing silent failures.
  • Using panic for normal error handling, which is discouraged.
  • Not returning errors from your own functions, making debugging harder.

Always prefer returning and checking errors over panicking.

Key Takeaways

Always check the error returned by functions using if err != nil.
Handle errors immediately to prevent unexpected program behavior.
Use clear error messages to help debugging.
Avoid ignoring errors or using panic for normal error handling.
Use linters to catch ignored errors during development.