Error Handling
In Go, error handling differs significantly from languages that use try/catch blocks. Go intentionally does not have try/catch mechanisms because it encourages a different approach to handling errors
. Instead, functions in Go often return multiple values, where the last value is typically an error
.
Example
package main
import (
"errors"
"fmt"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
result, err := divide(10, 2)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
result, err = divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}