Panic in Go

Go: Panic

What is Panic?

In Go, panic is a built-in function that causes a run-time error and stops the normal flow of a program. When a panic occurs, Go stops execution of the program and starts to unwind the stack, calling deferred functions along the way until it reaches the top of the stack. Once it reaches the top of the stack, the program terminates and prints the panic value and stack trace.

Panic Example in Go

The signature of the built-in panic function is provided below,

    func panic(interface{})  

How Panic works in Go

Here is an example to illustrate how panic works in Go:

    package main

    import "fmt"

    func main() {
        fmt.Println("Starting the program...")
        secondFunction()
        fmt.Println("Program ends.")
    }

    func secondFunction() {
        fmt.Println("Entering secondFunction...")
        thirdFunction()
        fmt.Println("Exiting secondFunction...")
    }

    func thirdFunction() {
        fmt.Println("Entering thirdFunction...")
        panic("Something went wrong!")
        fmt.Println("Exiting thirdFunction...")
    }

Explaination:

In above program, we have three functions: main(), secondFunction(), and thirdFunction(). When we run the program, it will start by calling main(), which prints "Starting the program...". Then main() calls secondFunction(), which prints "Entering secondFunction..." and then calls thirdFunction().

When thirdFunction() is called, it prints "Entering thirdFunction..." and then calls panic("Something went wrong!"). This panic function call causes the program to stop normal execution, unwind the stack, and start printing the stack trace, along with the error message "Something went wrong!".

As a result, the program prints the following output:

    Starting the program...
    Entering secondFunction...
    Entering thirdFunction...
    panic: Something went wrong!

    goroutine 1 [running]:
    main.thirdFunction()
            /path/to/panic-example/main.go:19 +0x66
    main.secondFunction()
            /path/to/panic-example/main.go:12 +0x4f
    main.main()
            /path/to/panic-example/main.go:8 +0x29
    exit status 2

As we can see from the output, the program stopped normal execution after the panic call in thirdFunction(), and printed a stack trace showing where the panic occurred, along with the error message "Something went wrong!". The program terminated with exit status 2.

Previous Article

Next Article