ZetCode

Golang panic function

last modified May 8, 2025

This tutorial explains how to use the panic built-in function in Go. We'll cover panic basics with practical examples of error handling and recovery.

The panic function is used to stop normal execution in Go. When panic is called, the program begins unwinding the stack, running deferred functions.

In Go, panic is typically used for unrecoverable errors. It should be reserved for exceptional cases where the program cannot continue execution.

Basic panic example

The simplest use of panic stops program execution immediately. This example demonstrates basic panic behavior.
Note: Panics should be used sparingly in production code.

basic_panic.go
package main

import "fmt"

func main() {
    fmt.Println("Starting program")
    
    panic("Something went terribly wrong!")
    
    fmt.Println("This line will never execute")
}

The program prints the first message then panics. The second message never prints as execution stops at the panic call.

Panic with recover

We can recover from panics using the recover function in deferred calls. This example shows panic recovery in action.

panic_recover.go
package main

import "fmt"

func mayPanic() {
    panic("a problem occurred")
}

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered from panic:", r)
        }
    }()
    
    mayPanic()
    
    fmt.Println("After mayPanic()")
}

The deferred function calls recover to catch the panic. The program continues execution after recovering from the panic.

Panic in goroutines

Panics in goroutines behave differently than in the main program. This example shows panic handling in concurrent code.

goroutine_panic.go
package main

import (
    "fmt"
    "time"
)

func worker() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Worker recovered:", r)
        }
    }()
    
    panic("Worker failed")
}

func main() {
    go worker()
    
    time.Sleep(1 * time.Second)
    fmt.Println("Main function continues")
}

The worker goroutine panics but recovers itself. The main goroutine continues execution unaffected by the worker's panic.

Panic with custom types

Panic can accept any value, including custom types. This example demonstrates using structured data with panic.

custom_panic.go
package main

import "fmt"

type ErrorDetails struct {
    Code    int
    Message string
}

func processInput(input int) {
    if input < 0 {
        panic(ErrorDetails{
            Code:    400,
            Message: "Negative input not allowed",
        })
    }
    fmt.Println("Processing input:", input)
}

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered:", r)
        }
    }()
    
    processInput(-5)
    fmt.Println("Program continues after recovery")
}

The function panics with a custom struct when invalid input is detected. The recovery handler can access the structured panic data.

Nested panic and recover

Panic and recover can be nested in function calls. This example shows complex panic propagation through multiple function calls.

nested_panic.go
package main

import "fmt"

func inner() {
    fmt.Println("Entering inner")
    panic("inner panic")
    fmt.Println("Leaving inner")
}

func middle() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Middle recovered:", r)
            panic("re-panicked in middle")
        }
    }()
    inner()
}

func outer() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Outer recovered:", r)
        }
    }()
    middle()
}

func main() {
    fmt.Println("Calling outer")
    outer()
    fmt.Println("Returned normally from outer")
}

The panic originates in inner, is caught and re-panicked in middle, and finally caught in outer. This shows how panics propagate up the call stack.

Source

Go language specification

This tutorial covered the panic function in Go with practical examples of error handling and recovery patterns.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Golang tutorials.