0
0
Goprogramming~5 mins

Panic behavior in Go

Choose your learning style9 modes available
Introduction

Panic is used in Go to stop the normal flow of a program when something unexpected happens. It helps to catch serious errors quickly.

When a program encounters a situation it cannot recover from, like a missing file.
When a function receives invalid input that should never happen.
During development, to catch bugs by stopping the program immediately.
When a critical resource is unavailable and continuing would cause wrong results.
Syntax
Go
panic("error message")

The panic function takes a message or value that explains the error.

When panic is called, the program stops normal execution and starts to unwind the stack.

Examples
This stops the program and shows the message "something went wrong".
Go
panic("something went wrong")
This function panics if the number is negative.
Go
func checkNumber(n int) {
    if n < 0 {
        panic("negative number not allowed")
    }
}
Sample Program

This program prints a start message, then panics with an error message. The line after panic does not run.

Go
package main

import "fmt"

func main() {
    fmt.Println("Start program")
    panic("unexpected error occurred")
    fmt.Println("This line will not run")
}
OutputSuccess
Important Notes

Panic should be used only for serious errors, not for normal error handling.

You can recover from panic using the recover function inside a deferred function.

Summary

Panic stops the program immediately with an error message.

Use panic for unexpected, unrecoverable errors.

Normal errors should be handled with error values, not panic.