Lesson 8 of 60 · Go
Error Handling & Defer
Duration: 20 minutes
Errors in Go
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
Go does not have exceptions. Functions return an error value which must be checked.
func ReadFile(name string) ([]byte, error) {
return os.ReadFile(name)
}
data, err := ReadFile("config.json")
if err != nil {
log.Fatalf("cannot read file: %v", err)
}
Creating custom errors
var ErrNotFound = errors.New("resource not found")
Wrapping errors (Go 1.13+)
if err != nil {
return fmt.Errorf("open %s: %w", name, err)
}
The defer statement
Runs after the surrounding function returns.
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil { return err }
defer in.Close()
out, err := os.Create(dst)
if err != nil { return err }
defer out.Close()
_, err = io.Copy(out, in)
return err
}