ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)
Set your Publisher ID in src/config/ads.ts to display live ads.
Go (Golang) Tutorial• 7 min read
Functions, Multiple Return Values & Errors as Values
Why Go has no try/catch exceptions: The if err != nil convention
Go does NOT have traditional try...catch exceptions. Instead, functions return errors as explicit values, encouraging engineers to treat failure as a standard control flow state.
The `if err != nil` Architecture
Multiple Returns: Functions can return multiple values: func Divide(a, b float64) (float64, error).
The error interface: Built-in interface with a single method: Error() string.
Idiom: Return (result, nil) on success; return (zeroValue, err) on failure.
Explicit Error Handling Pattern
package main
import (
"errors"
"fmt"
)
func divide(numerator, denominator float64) (float64, error) {
if denominator == 0 {
return 0, errors.New("cannot divide by zero")
}
return numerator / denominator, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error caught:", err)
return
}
fmt.Println("Result:", result)
}ADVERTISEMENT
Google AdSense Slot (inContentBanner)
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
How does Go handle errors compared to languages like Java, Python, or C++?