DEV Community

Cover image for Golang panic and recover

Posted on


Golang panic and recover

In Golang, Panic is a function that stops the ordinary flow of control and starts panicking.

Errors are for abnormal conditions during program execution, but there are some cases where the program cannot continue executing after something went wrong.

In that case you can use panic to terminate the program.

A simple example is creating a new file, which is a requirement of the program. If the file cannot be created, the control flow must stop:

    _, err := os.Create("/tmp/file")
    if err != nil {


The program below demonstrates the use of panic(). A program calls a function sayHello(name), which on normal situations outputs the name.

But what if a name is not specified? Then something went wrong: panic.

package main

import (  

func sayHello(name *string) {  
    if name == nil {
        panic("runtime error: name cannot be nil")
    fmt.Printf("Hello %s\n", *name)

func main() {  

This outputs in the terminal:

  ~ go run pan.go 
panic: runtime error: name cannot be nil

goroutine 1 [running]:
        /home/frank/pan.go:15 +0x3a
exit status 2


If the panic situation happens, the program terminates. In the real world, this is not good.

The application terminating on error? Nobody wants that. Instead, you need a mechanism to recover from the error.

This is a Panic Situation
Recovery function
Main block executed

In code that looks like this:

package main

import (

func makePanic() {
    defer recoveryFunction()
    panic("This is a Panic Situation")

func recoveryFunction() {
    if recoveryMessage := recover(); recoveryMessage != nil {
    fmt.Println("Recovery function")

func main() {
    fmt.Println("Main block executed")

Related links:

Top comments (0)

12 Gorgeous UI Components for Your Design Inspiration

12 Gorgeous UI components for your design inspiration: cards, text, buttons, checkboxes, icons, loaders and menus.