How to Handle Errors in Go: Simple and Effective Techniques
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.
package main import ( "fmt" "strconv" ) func main() { // Ignoring error returned by strconv.Atoi number, _ := strconv.Atoi("abc") fmt.Println("Number is", number) }
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.
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) }
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
panicfor 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
error returned by functions using if err != nil.