Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

We Panic

  • panic
  • raise

We can also initiate our own "panic" by calling the panic function.

package main

import (
	"fmt"
)

func main() {
	fmt.Println("before")

	x := div(6, 2)
	fmt.Println(x)

	fmt.Println("middle")

	y := div(6, 0)
	fmt.Println(y)

	fmt.Println("after")
}

func div(a, b int) int {
	if b == 0 {
		panic("Do you expect us do divide by 0?")
	}

	c := a / b
	return c
}
before
3
middle
panic: Do you expect us do divide by 0?

goroutine 1 [running]:
main.div(...)
	/home/gabor/work/slides/golang/examples/we-panic/we_panic.go:23
main.main()
	/home/gabor/work/slides/golang/examples/we-panic/we_panic.go:15 +0x151
exit status 2