Introduction
Error handling helps your program deal with problems smoothly instead of crashing. It lets you fix or report issues so users have a better experience.
Error handling helps your program deal with problems smoothly instead of crashing. It lets you fix or report issues so users have a better experience.
value, err := someFunction() if err != nil { // handle the error }
file, err := os.Open("file.txt") if err != nil { fmt.Println("Error opening file:", err) return }
num, err := strconv.Atoi("abc") if err != nil { fmt.Println("Conversion error:", err) }
This program tries to open a file named "missing.txt". Since the file does not exist, it prints an error message instead of crashing.
package main import ( "fmt" "os" ) func main() { file, err := os.Open("missing.txt") if err != nil { fmt.Println("Failed to open file:", err) return } defer file.Close() fmt.Println("File opened successfully") }
Always check errors returned by functions to avoid unexpected crashes.
Handling errors early helps you find and fix problems faster.
Error handling keeps programs running smoothly when things go wrong.
In Go, errors are values you check after calling functions.
Handling errors improves user experience and program reliability.
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(err)
} else {
fmt.Println(result)
}
}package main
import "fmt"
func openFile(name string) error {
// pretend to open file
return nil
}
func main() {
err := openFile("data.txt")
if err == nil {
fmt.Println("Error opening file")
} else {
fmt.Println("File opened successfully")
}
}Pass the test and this pattern moves unknown