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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Error Handling & Defer | Go Programming Bootcamp lesson | BraveProgrammer
  1. Courses
  2. /
  3. Go Programming Bootcamp

Lesson 8 of 60

·Go

Error Handling & Defer

20 minutes

Course progress13%

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) {
     os.ReadFile(name)
}

data, err := ReadFile()
 err !=  {
    log.Fatalf(, err)
}
return
"config.json"
if
nil
"cannot read file: %v"

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))).
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from Go Programming BootcampBrowse activities
Previous lessonStructs, Methods, and InterfacesContinue to lesson 9Pointers, Allocation, and the Garbage CollectorBack to Go Programming Bootcamp curriculum