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…

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Explains 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

  1. Write a Go program that panics, recovers and then finally prints a message.
  2. 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.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help