Defer Panic and Recover in Go

List Topics
February 15, 2025
No Comments
4 min read

In Go, error handling is managed using defer, panic, and recover. These mechanisms help in handling unexpected errors and ensuring proper resource cleanup.

1. defer Statement

🔹 defer is used to delay the execution of a function until the surrounding function returns. It is mainly used for cleanup operations like closing files, releasing locks, etc.

🔹 Syntax of defer

Go
defer functionName()
  • The deferred function executes after the surrounding function completes.
  • Multiple defer statements are executed in LIFO (Last In, First Out) order.

🔹 Example of defer

Go
package main

import "fmt"

func main() {
    fmt.Println("Start")
    
    defer fmt.Println("Deferred: This executes last")
    
    fmt.Println("Middle")
}

🔹 Output:

Bash
Start
Middle
Deferred: This executes last

👉 Explanation:

  • "Deferred: This executes last" runs at the end because it is deferred.

🔹 Multiple defer Example (LIFO Order)

Go
package main

import "fmt"

func main() {
    defer fmt.Println("First")
    defer fmt.Println("Second")
    defer fmt.Println("Third")
    
    fmt.Println("Main function executed")
}

🔹 Output:

Bash
Main function executed
Third
Second
First

👉 Explanation:

  • The last defer statement is executed first.

2. panic in Go

🔹 panic is used to stop program execution immediately.
🔹 It is usually used when the program cannot recover from an error.
🔹 When panic occurs, it executes deferred statements before stopping the program.

🔹 Syntax of panic

Go
panic("Error message")

🔹 Example of panic

Go
package main

import "fmt"

func main() {
    fmt.Println("Start")
    
    panic("Something went wrong!")  // Program stops here
    
    fmt.Println("End") // This line will not execute
}

🔹 Output:

Bash
Start
panic: Something went wrong!

👉 Explanation:

  • "Start" prints.
  • panic("Something went wrong!") stops execution.
  • "End" does not execute.

🔹 panic with defer (Deferred function still runs)

Go
package main

import "fmt"

func main() {
    defer fmt.Println("This will execute before panic stops the program")

    fmt.Println("Before panic")
    panic("Something went wrong!")
}

🔹 Output:

Bash
Before panic
This will execute before panic stops the program
panic: Something went wrong!

👉 Explanation:

  • Deferred function still runs before panic stops execution.

3. recover in Go

🔹 recover is used to catch a panic and prevent the program from crashing.
🔹 It is used inside a defer function to handle errors gracefully.

🔹 Syntax of recover

Go
recover()
  • recover() returns nil if there is no panic.
  • It stops the panic and resumes execution.

🔹 Example of recover Handling Panic

Go
package main

import "fmt"

func main() {
    defer handlePanic()

    fmt.Println("Start")
    panic("Something went wrong!")
    fmt.Println("End")  // This line will NOT execute
}

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

🔹 Output:

Bash
Start
Recovered from panic: Something went wrong!

👉 Explanation:

  • panic("Something went wrong!") occurs.
  • handlePanic() runs because of defer.
  • recover() catches the panic and prevents a crash.

🔹 Example: panic, defer, and recover Together

Go
package main

import "fmt"

func main() {
    fmt.Println("Main started")
    
    safeFunction()

    fmt.Println("Main function continues")
}

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

    fmt.Println("Inside safeFunction")
    panic("Critical error!")  // Triggers panic
    fmt.Println("This line will not execute")
}

🔹 Output:

Bash
Main started
Inside safeFunction
Recovered from: Critical error!
Main function continues

👉 Explanation:

  • panic("Critical error!") is triggered.
  • recover() inside defer catches the panic.
  • The program continues execution instead of crashing.

Key Takeaways

FeatureDescription
deferDelays execution of a function until the surrounding function completes. Useful for cleanup tasks.
panicStops program execution immediately. Used for critical errors.
recoverCaptures panic and prevents program crash. Used inside defer.

āĻŦāĻžāĻ‚āϞāĻž āĻŦā§āϝāĻžāĻ–ā§āϝāĻž

1. defer āϕ⧀?

🔹 defer āĻŦā§āϝāĻŦāĻšāĻžāϰ āĻ•āϰāĻž āĻšāϝāĻŧ āϕ⧋āύ⧋ āĻĢāĻžāĻ‚āĻļāύ⧇āϰ āĻāĻ•ā§āϏāĻŋāĻ•āĻŋāωāĻļāύ āĻŦāĻŋāϞāĻŽā§āĻŦāĻŋāϤ āĻ•āϰāϤ⧇āĨ¤
🔹 āϏāĻžāϧāĻžāϰāĻŖāϤ āĻĢāĻžāχāϞ āĻ•ā§āϞ⧋āϜ, āϰāĻŋāϏ⧋āĻ°ā§āϏ āϰāĻŋāϞāĻŋāϜ āĻ•āϰāĻžāϰ āϜāĻ¨ā§āϝ āĻŦā§āϝāĻŦāĻšāĻžāϰ āĻ•āϰāĻž āĻšāϝāĻŧāĨ¤

✅ defer āĻāϰ āωāĻĻāĻžāĻšāϰāĻŖ

Go
package main

import "fmt"

func main() {
    fmt.Println("Start")
    
    defer fmt.Println("āĻāϟāĻŋ āϏāĻŦāĻļ⧇āώ⧇ āϚāϞāĻŦ⧇")
    
    fmt.Println("Middle")
}

🔹 āφāωāϟāĻĒ⧁āϟ:

Bash
Start
Middle
āĻāϟāĻŋ āϏāĻŦāĻļ⧇āώ⧇ āϚāϞāĻŦ⧇

2. panic āϕ⧀?

🔹 panic āĻšāϞ⧋ āϭ⧁āϞ āĻšāϞ⧇ āĻĒā§āϰ⧋āĻ—ā§āϰāĻžāĻŽ āĻĨāĻžāĻŽāĻžāύ⧋āϰ āϜāĻ¨ā§āϝāĨ¤
🔹 āĻāϟāĻŋ āĻāĻ•ā§āϏāĻŋāĻ•āĻŋāωāĻļāύ āϤāĻžā§ŽāĻ•ā§āώāĻŖāĻŋāĻ•āĻ­āĻžāĻŦ⧇ āĻŦāĻ¨ā§āϧ āĻ•āϰ⧇āĨ¤

✅ panic āĻāϰ āωāĻĻāĻžāĻšāϰāĻŖ

Go
package main

import "fmt"

func main() {
    fmt.Println("Start")
    
    panic("āϏāĻŽāĻ¸ā§āϝāĻž āĻĻ⧇āĻ–āĻž āĻĻāĻŋāϝāĻŧ⧇āϛ⧇!")  // āĻĒā§āϰ⧋āĻ—ā§āϰāĻžāĻŽ āĻāĻ–āĻžāύ⧇ āĻĨ⧇āĻŽā§‡ āϝāĻžāĻŦ⧇
    
    fmt.Println("End") // āĻāϟāĻŋ āĻāĻ•ā§āϏāĻŋāĻ•āĻŋāωāϟ āĻšāĻŦ⧇ āύāĻž
}

🔹 āφāωāϟāĻĒ⧁āϟ:

Bash
Start
panic: āϏāĻŽāĻ¸ā§āϝāĻž āĻĻ⧇āĻ–āĻž āĻĻāĻŋāϝāĻŧ⧇āϛ⧇!

3. recover āϕ⧀?

🔹 recover āĻšāϞ⧋ panic āĻ•ā§āϝāĻžāĻĒāϚāĻžāϰ āĻ•āϰāĻžāϰ āωāĻĒāĻžāϝāĻŧāĨ¤
🔹 āĻāϟāĻŋ defer āĻāϰ āĻ­āĻŋāϤāϰ⧇ āĻŦā§āϝāĻŦāĻšāĻžāϰ āĻ•āϰāĻž āĻšāϝāĻŧ panic āĻĨ⧇āϕ⧇ āϰāĻ•ā§āώāĻž āĻĒ⧇āϤ⧇āĨ¤

✅ recover āĻāϰ āωāĻĻāĻžāĻšāϰāĻŖ

Go
package main

import "fmt"

func main() {
    defer handlePanic()

    fmt.Println("Start")
    panic("āĻ•āĻŋāϛ⧁ āĻāĻ•āϟāĻž āϏāĻŽāĻ¸ā§āϝāĻž āĻšāϝāĻŧ⧇āϛ⧇!")
}

func handlePanic() {
    if r := recover(); r != nil {
        fmt.Println("āĻĒā§āϝāĻžāύāĻŋāĻ• āĻĨ⧇āϕ⧇ āωāĻĻā§āϧāĻžāϰ:", r)
    }
}

🔹 āφāωāϟāĻĒ⧁āϟ:

Bash
Start
āĻĒā§āϝāĻžāύāĻŋāĻ• āĻĨ⧇āϕ⧇ āωāĻĻā§āϧāĻžāϰ: āĻ•āĻŋāϛ⧁ āĻāĻ•āϟāĻž āϏāĻŽāĻ¸ā§āϝāĻž āĻšāϝāĻŧ⧇āϛ⧇!

āωāĻĒāϏāĻ‚āĻšāĻžāϰ

✅ defer → āĻĻ⧇āϰāĻŋāϤ⧇ āϚāĻžāϞāĻžāϝāĻŧ
✅ panic → āϤāĻžā§ŽāĻ•ā§āώāĻŖāĻŋāĻ•āĻ­āĻžāĻŦ⧇ āĻĨāĻžāĻŽāĻžāϝāĻŧ
✅ recover → panic āĻ āĻŋāĻ• āĻ•āϰ⧇

🚀 Go-āϤ⧇ defer, panic, āĻ“ recover āĻŦā§āϝāĻŦāĻšāĻžāϰ āĻ•āϰ⧇ āĻāĻĢāĻŋāĻļāĻŋāϝāĻŧ⧇āĻ¨ā§āϟ āĻāϰāϰ āĻšā§āϝāĻžāĻ¨ā§āĻĄāϞāĻŋāĻ‚ āĻ•āϰāĻž āϝāĻžāϝāĻŧāĨ¤

Š2025 Linux Bangla | Developed & Maintaind by Linux Bangla.