Concept Flow - Handling errors
Start function
Try operation
Error returned?
No→Use result
Yes
Handle error
End function
The program tries an operation, checks if an error occurred, handles it if yes, otherwise uses the result.
package main import ( "errors" "fmt" ) func divide(a, 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) } else { fmt.Println("Result:", result) } }
| Step | Action | Condition | Result | Output |
|---|---|---|---|---|
| 1 | Call divide(10, 0) | b == 0? | True | Return error "cannot divide by zero" |
| 2 | In main, check err != nil | err != nil? | True | Print "Error: cannot divide by zero" |
| 3 | End program | - | - | - |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| a | 10 | 10 | 10 | 10 |
| b | 0 | 0 | 0 | 0 |
| result | undefined | 0 | 0 | 0 |
| err | undefined | error("cannot divide by zero") | error("cannot divide by zero") | error("cannot divide by zero") |
Go error handling: - Functions return (value, error) - Check if error != nil after call - Handle error before using value - Use errors.New() to create errors - Prevent program crashes by checking errors