Working with Deferred Functions in Go

11.23.2021

Intro

Go doesn't have an exception mechanism, instead we have panic. During run time, if there is an execution problem, Go will throw a panic. This will stop code execution, completed all deferred functions, then log a message. In this article, we will learn how to use Panic in Go.

Example Panic

One common example is access the index of an array that is out of bounds.

var arr [3]string

// Throws panic
fmt.Println(myarr[4])
./prog.go:32:34: invalid array index 4 (out of bounds for 3-element array)

Calling Panic Manually

We can also call panic when something is not supposed to happen. For example, let's say we have a switch statement that has no default option. If a user doesn't supply a correct value, we can call panic.

option := 3

switch option {
	case 1:
		fmt.Println("Option 1")
	case 2:
		fmt.Println("Option 2")
	default:
		panic(fmt.Println("Option is invalid"))
}	
panic: Option is invalid

goroutine 1 [running]:
main.main()
        C:/Users/krh12/Documents/r-data-vis/GoLang/panic/main.go:20 +0x27
exit status 2

The Full Example

Here is the full example code. You can run this by copying the contents into a file called main.go and then running go run main.go.

package main

import (
	"fmt"
)

func deferredCall() {
	fmt.Println("Print Second")
}

func main() {
	option := 3

	switch option {
	case 1:
		fmt.Println("Option 1")
	case 2:
		fmt.Println("Option 2")
	default:
		panic("Option is invalid")
	}
}