Go course

ErrorsPanic vs Error

Go

Display

Theme

Errors · Code example

Panic vs Error

Besides returning an error, Go has a second mechanism: panic. When a panic happens, the function stops immediately, Go "unwinds" the call stack, and, if nothing catches it, the program crashes with a message and a stack trace.

func ambilLevel(level int) string {
	if level < 1 {
		panic("level tidak boleh kurang dari 1")
	}
	return fmt.Sprintf("Level %d", level)
}

Panics are also triggered by Go itself at run time, for example integer division by zero or a failed type assertion without comma ok.

When to use which?

SituationUse
Failures that are expected to happen: bad user input, a missing file, insufficient balance, a dropped networkerror
Conditions that should be impossible, a sign of a bug in the programpanic
A failure during initialization that makes it impossible for the program to runpanic (or log.Fatal)

Rule of thumb: almost always use error. A good library doesn't crash the programs that use it just because of bad input.

recover (a quick look)

A panic can be caught with recover inside a deferred function. defer schedules a function to run right before the surrounding function finishes, including when it panics.

func aman() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("pulih dari panic:", r)
		}
	}()
	panic("ada yang salah")
}

recover is rarely used in everyday code; usually only at the program's "boundary", such as a web server that doesn't want the whole process to die because of one bad request.

Try it yourself

The editor holds an example comparing the two approaches. Press Run, then try:

  • Change bagiAman(10, 0) to bagiAman(10, 2).
  • Remove the defer ... recover block in jalankanDenganPengaman and see what happens when the program runs.
main.go
package main

import (
	"errors"
	"fmt"
)

// Pendekatan 1: kegagalan dikembalikan sebagai error.
func bagiAman(a, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("pembagi tidak boleh nol")
	}
	return a / b, nil
}

// Pendekatan 2: kegagalan memicu panic.
func bagiPanik(a, b int) int {
	if b == 0 {
		panic("pembagi tidak boleh nol")
	}
	return a / b
}

// jalankanDenganPengaman menangkap panic dari f agar program tidak crash.
func jalankanDenganPengaman(nama string, f func()) {
	defer func() {
		if r := recover(); r != nil {
			fmt.Printf("[%s] pulih dari panic: %v\n", nama, r)
		}
	}()
	f()
	fmt.Printf("[%s] selesai tanpa panic\n", nama)
}

func main() {
	hasil, err := bagiAman(10, 0)
	if err != nil {
		fmt.Println("Error ditangani dengan rapi:", err)
	} else {
		fmt.Println("Hasil:", hasil)
	}

	jalankanDenganPengaman("bagi 10/2", func() {
		fmt.Println("Hasil:", bagiPanik(10, 2))
	})

	jalankanDenganPengaman("bagi 10/0", func() {
		fmt.Println("Hasil:", bagiPanik(10, 0))
	})

	fmt.Println("Program tetap berjalan sampai akhir.")
}

Output

Go runtime not loaded yet

Press Run to see what the program prints.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + S: tidy the code (gofmt)