Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Go Programming Bootcamp

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
}

Info

Common use cases for defer: closing files, unlocking mutexes, measuring elapsed time (defer log.Printf("took %v", time.Since(start))).

Previous: Structs, Methods, and InterfacesNext: Pointers, Allocation, and the Garbage Collector