Go (Golang) / Control Flow and Functions
Understanding Defer, Panic, and Recover in Go
This tutorial will guide you through the concepts of Defer, Panic, and Recover in Go. These are fundamental concepts that you need to understand in order to properly handle errors…
Section overview
5 resourcesExplains how to use conditional statements, loops, and functions in Go.
1. Introduction
1.1. Brief explanation of the tutorial's goal
This tutorial aims to demystify three essential concepts in Go programming — Defer, Panic, and Recover. These mechanisms are powerful tools in error handling and maintaining program execution flow in Go.
1.2. What the user will learn
By the end of this tutorial, you will have a clear understanding of how to use Defer, Panic, and Recover effectively in your Go programs. You will learn how to manage function executions and control error propagation in your code.
1.3. Prerequisites
Basic knowledge of Go programming language is recommended before going through this tutorial. Familiarity with error handling concepts in general would be helpful but not necessary.
2. Step-by-Step Guide
2.1. Defer
In Go, defer is used to ensure that a function call is performed later in a program's execution, usually for purposes of cleanup. defer is often used where ensure and finally would be used in other languages.
func example() {
defer fmt.Println("world")
fmt.Println("hello")
}
In the above example, even though defer fmt.Println("world") appears before fmt.Println("hello"), it is executed after fmt.Println("hello").
2.2. Panic
Panic is a built-in function that stops the ordinary flow of control and begins panicking. When the function F calls panic, execution of F stops, and any deferred functions in F are executed normally, and then F returns to its caller.
func example() {
defer fmt.Println("world")
panic("something bad happened")
fmt.Println("hello")
}
In this example, panic stops the execution, defer functions are then executed, and then the program crashes with a log message: panic: something bad happened.
2.3. Recover
Recover is a built-in function that regains control of a panicking goroutine. Recover is only useful inside deferred functions.
func example() {
defer func() {
if err := recover(); err != nil {
fmt.Println("Recovered in f", err)
}
}()
panic("something bad happened")
}
Here, recover is used to catch the panic and regain control of the program. The log message will be: Recovered in f something bad happened.
3. Code Examples
package main
import "fmt"
func main() {
fmt.Println("start")
panicAndRecover()
fmt.Println("end")
}
func panicAndRecover() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered", r)
}
}()
fmt.Println("about to panic")
panic("something bad happened")
fmt.Println("done panicking")
}
This program will output:
start
about to panic
Recovered something bad happened
end
4. Summary
In this tutorial, we've covered the basics of defer, panic, and recover in Go. These are powerful concepts that allow you to control the flow of your programs and handle errors effectively.
5. Practice Exercises
- Write a Go program that panics, recovers and then finally prints a message.
- Write a function that defers 10 function calls, each printing one of the numbers 1 to 10. Make sure that they print in reverse order.
Solutions and explanations to these exercises will help solidify your understanding of these concepts. After you have attempted the exercises, check your solutions against those provided and revisit the sections if necessary. Happy coding!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article