Error Handling (Explicit Check)
Go does not support try-catch exception handling. Instead, Go requires errors to be returned explicitly as return values, promoting clear, robust code design.
1 Explicit Return Values & The errors Package
In Go, if a function can fail, it returns an `error` object as its last return value. The caller must explicitly check if the returned error is not nil: `if err != nil { // handle error }`. While verbose, this ensures errors are handled immediately, preventing silent failures and unhandled runtime crashes.
2 Error Handling Code
Let's run a program demonstrating division verification checks and error handling patterns:
Go — Error Checks
▶ Run Code
package main
import (
"errors"
"fmt"
)
func validateUser(age int) (string, error) {
if age < 0 {
return "", errors.New("age cannot be negative")
}
return fmt.Sprintf("User age verified: %d", age), nil
}
func main() {
msg, err := validateUser(-5)
// Explicit error check
if err != nil {
fmt.Println("Error caught: ", err.Error())
} else {
fmt.Println(msg)
}
}
3 Code Challenge
Challenge: Write a function called `Sqrt` that returns the square root of a float64. Return a custom error if the number is negative. Call the function in `main()` with a negative argument, check the error, and print the output.