25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started โ†’

Interactive Go ยท Lesson

Error Handling

Go doesn’t use exceptions. Instead, functions that can fail return an error as their last value, and you check it right away. This is the famous if err != nil idiom:

result, err := doRisky()
if err != nil {
    fmt.Println("it failed:", err)
    return
}
// safe to use result here

A nil error means success. You create errors with errors.New("message") or fmt.Errorf("got %d", n).

Your Quest

drink(0) returns an error. Check err: if it’s not nil, print the error; otherwise print Potion drunk!.

Expected output:

no potions left

Hint

if err != nil { fmt.Println(err) } else { fmt.Println("Potion drunk!") }.

Additional Scrolls of Wisdom