Panic in Golang

In this tutorial you will learn panic in Go programming language, why it is significant, how to declare in Golang, uses of panic in Golang, etc.

What is Panic in Golang?

In go language, there is no exception like in other languages. For example, if you try to open a file and that file does not exist Golang will return some error values not exceptions because exceptions are not considered in Golang.
In the Go programming language instead of the word “exception”, you can use “panic”. The program or application continues to function or execute but it is in a situation called “panic” because the program doesn’t know what to do in such a situation.
An exception is any unexpected event that affects the normal flow of instruction in many other programs like Java, c#, c++ during their execution. In Golang the word exception is replaced by the word panic.

GO : Panic

Panic definition in Golang

  •   A panic function can be defined as an exception in Golang which is a built-in function under Golang packages. 
  •   When a panic function is found in the Go program during its runtime the compilers terminates its execution from that point.
  •   The flow of control is terminated and starts panicking from panic function.

Panic example

Let us consider an example


package main
import (
 "fmt"
)

func main() {
    a,b := 1,0   // variable a & b are declared and initialized
    result := a/b        // division operation
    fmt.Println(result)
    }

Output:


panic: runtime error: integer divide by zero

goroutine 1 [running]:
main.main()
 /home/gqcsh6/prog.go:11 +0x11

Consider the above code which declares variables a & b and initialized with values 1 and 0. a = 1 & b =0. The division operation is performed between a & b variables and stores the final value in another declared variable called result.

GO : Panic

We know the operation is the invalid type and will show an error. When we run the code during runtime itself it generates a panic. The runtime error is printed as an integer divided by zero. Also, mention the stack trace to denote where the error has occurred like 

main.main()

    /home/gqcsh6/prog.go:11 +0x11

In order to avoid these situations, the built-in panic function can be used in Golang.

How to declare panic in Golang?

In go language, the programmer can write a panic code when the program enters into a situation where it cannot continue its execution. In such cases, the built-in panic function can be used.

Syntax


func panic( interface{} )

  •   The string or arguments passed to the function panic will be displayed when the program terminates.
GO : Panic

Let us see how to add panic in a Go program


package main
import  "fmt"
func main() {
 
    fmt.Println("start Go program")
    panic(" built in panic keyword gives error msg")  // panic keyword
    fmt.Println("End Go program")
    }

Output:


panic:  built in panic keyword gives error msg

goroutine 1 [running]:
main.main()
 /home/vSbday/prog.go:6 +0x95

In the above output, you can observe that the error message printed out is the exact message or string we have passed while stating the panic keyword.

When to use panic in Golang?

  •  The panic function should be used only when a program cannot continue its execution. For example: when a webserver fails to bind to a port use the panic function nothing else can be done there.
  •  Use panic in case of programmer error.

Example: Suppose a method accepting a pointer as a parameter is called using nil argument it falls under programmer error so better use the panic function.

How does defer work with function panic in Golang?

In our previous tutorial, we already discussed defer in Golang.
A defer statement in go programming language delays the execution of a statement, function, or method defined using defer keyword. (check to defer tutorial for better understanding). The defer statement is the last one printed after all the execution described inside a function, which is printed just before the method terminates.

The panic function will just stop the execution till the last statement or function before the panic function is met and return an error message.

Let us consider the below example


package main
import "fmt"

func Name(firstName *string, lastName *string) {
 defer fmt.Println("Name function deferred call")
 if firstName == nil {
  panic("runtime error: first name cannot be nil")
 }
 if lastName == nil {
  panic("runtime error: last name cannot be nil")
 }
 fmt.Printf("%s %s\n", *firstName, *lastName)
 fmt.Println("return from Name")
}
func main() {
 defer fmt.Println("main() deffered call")
 firstName := "Elon"
 Name(&firstName, nil)
 fmt.Println("return from main")
}

Output:


Name function deferred call
main() deffered call
panic: runtime error: last name cannot be nil

goroutine 1 [running]:
main.Name(0x7f66dc945108, 0x60)
 /tmp/sandbox2801026756/prog.go:13 +0x197
main.main()
 /tmp/sandbox2801026756/prog.go:22 +0x8c
Program exited.

Now let's understand the source code to get the clear working of defer and panic.
The execution begins from the main function where it is defined as a printing statement with deferring. The main function just delays or omits its current execution sometime later and moves to the next instruction in the main function.

GO : Panic

The control goes to function Name and prints deferred function inside it and then the delayed deferred function inside the main.

GO : Panic

The control now reaches the top-level function of the program prints the panic message followed by the stack trace and then terminates as shown in the above output.

GO : Panic

How does panic work with a slice in Golang?

Let us understand with an example. Consider the below program using slice.


package main
import "fmt"

func main() {
    names := []string{  //slice data type
        "Learn eTutorials",     // index 0
        "Golang",  //index 1
        "panic tutorial", //index 2
    }    
    fmt.Println(names[0])
    fmt.Println(names[2])
}

Output:


Learn eTutorials
panic tutorial

To better understand the above code refer slice tutorial which we have discussed.
Now let us come to the concept of panic how panic is occurring in the same program.
We know in a slice the indexing starts from number 0. When an out-of-bound index is requested to print that exception or error is raised by the panic function in Golang during its runtime.
Let us see the example for the same


package main
import "fmt"

func main() {
    names := []string{  //slice data type
        "Learn eTutorials",     // index 0
        "Golang",  //index 1
        "panic tutorial", //index 2
    }
    
    //fmt.Println(names[0]) commented
    //fmt.Println(names[2]) commented
    
    fmt.Println(names[4])
}

Output:


panic: runtime error: index out of range [4] with length 3

goroutine 1 [running]:
main.main()
 /home/2x9Qrt/prog.go:15 +0x1d
GO : Panic

You can clearly see from the output slice index range asked to print by the programmer is out of index there exist only index up to 2.
name[0] := Learn eTutorials
name[1] := Golang
name[2] := panic tutorial

GO : Panic