Tsallaka zuwa abun ciki
Justice Tech School

panic and recover

panic stops normal flow. recover inside a deferred function catches it. Use for truly exceptional cases only.

Example
package main

import "fmt"

func safe() (msg string) {
	defer func() {
		if r := recover(); r != nil {
			msg = fmt.Sprint("recovered: ", r)
		}
	}()
	panic("boom")
}

func main() {
	fmt.Println(safe())
}

Result

recovered: boom

Exercise

Catch a panic.

()

Quiz Test

Where does recover work?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.