Instead of exceptions, Go's normal style is to return an error value and have the caller check it. This approach keeps errors from hiding — you can see them clearly right in the code flow.
go
package main
import (
"errors"
"fmt"
)
func divide(a int, b int) (int, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Result:", result)
}divide function returns a result and an error. When there's no error, it returns nil; when there is one, it returns an error value carrying a message.
You should see
Error: cannot divide by zeroInfo
if err != nil might look repetitive once you notice it everywhere, but it's an important style for keeping Go code readable.