Learn how to handle errors properly in your Go programs.
Unlike Python or Java, Go does not use `try/catch` for error handling. Instead, it returns `error` values from functions.
This approach makes error handling explicit, improving readability and reducing hidden errors.
Errors are returned from functions and should be checked immediately.
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero is not allowed")
}
return a / b, nil
}
Sometimes, `panic` is necessary for stopping execution immediately.
func main() {
fmt.Println("Starting the program")
panic("Critical error!")
fmt.Println("This will never be printed")
}
However, `recover` can be used to prevent a full crash:
func handleError() {
if r := recover(); r != nil {
fmt.Println("Recovered from error:", r)
}
}
func main() {
defer handleError()
panic("A fatal error occurred!")
}
⚠️ `recover` should only be used in rare cases to prevent abrupt crashes.
errors.go
.package main
import (
"fmt"
"os"
)
func openFile(name string) (string, error) {
file, err := os.Open(name)
if err != nil {
return "", fmt.Errorf("Error: cannot open %s - %v", name, err)
}
defer file.Close()
return "File opened successfully!", nil
}
func main() {
message, err := openFile("myfile.txt")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(message)
}
}
Error: cannot open myfile.txt - open myfile.txt: no such file or directory
📚 Learn more about error handling in Go:
Official Go Documentation🚀 Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊