Go - Defer, Panic, and Recover
Last Updated :
23 Jul, 2025
Error handling is crucial for writing robust and maintainable code in Go. It provides three key tools:
- defer: Delays function execution until the surrounding function completes.
- panic: Immediately stops the program when a critical error occurs.
- recover: Regains control after a panic to prevent a crash.
Go treats errors as values, usually returned as the last function result. When an error is too severe, panic and recover help manage unexpected failures.
1. defer
in Go
The defer
statement is used to ensure that a function call is executed later in the program’s execution, usually for cleanup purposes. This is particularly useful for releasing resources like file handles, database connections, or mutex locks.
How defer
Works?
When you use defer
, the deferred function is pushed onto a stack. When the surrounding function returns, the deferred functions are executed in Last In, First Out (LIFO) order.
Example:
package main
import "fmt"
func main() {
// defer the execution of Println() function
defer fmt.Println("Three")
fmt.Println("One")
fmt.Println("Two")
}
Output:
One
Two
Three
In this example, the fmt.Println("Three")
statement is deferred, so it executes after fmt.Println("One")
and fmt.Println("Two")
.
Multiple defer
Statements
When multiple defer
statements are used, they are executed in LIFO order.
Example:
package main
import "fmt"
func main() {
defer fmt.Println("One")
defer fmt.Println("Two")
defer fmt.Println("Three")
}
Output:
Three
Two
One
Here, the last defer
statement (fmt.Println("Three")
) is executed first, and the first defer
statement (fmt.Println("One")
) is executed last.
2. Golang panic
The panic
statement is used to immediately stop the execution of a program when an unrecoverable error occurs. When a panic
is triggered, the program starts unwinding the stack, running any deferred functions along the way, and then crashes with an error message.
How panic
Works?
When panic
is called, the normal flow of the program is interrupted. The program prints a panic message, followed by a stack trace, and then terminates.
Example: Basic panic
Usage
package main
import "fmt"
func main() {
fmt.Println("Help! Something bad is happening.")
panic("Ending the program")
fmt.Println("Waiting to execute") // This line will not execute
}
Output:
Help! Something bad is happening.
panic: Ending the program
In this example, the program terminates when it encounters the panic
statement, so the line fmt.Println("Waiting to execute")
is never executed.
Example:
Let’s look at a more practical example where panic
is used to handle division by zero.
Go
package main
import "fmt"
func division(num1, num2 int) {
// if num2 is 0, program is terminated due to panic
if num2 == 0 {
panic("Cannot divide a number by zero")
} else {
result := num1 / num2
fmt.Println("Result: ", result)
}
}
func main() {
division(4, 2)
division(8, 0) // This will cause a panic
division(2, 8) // This line will not execute
}
Output:
Result: 2
panic: Cannot divide a number by zero
Here, the program panics when it attempts to divide by zero, and the subsequent function call (division(2, 8)
) is never executed.
3. Recover
While panic
is used to terminate a program, recover
is used to regain control after a panic
has occurred. This allows the program to handle the error gracefully instead of crashing.
The recover
function is used inside a deferred function to catch the panic message and resume normal execution. If recover
is called outside of a deferred function, it has no effect.
Example: Using recover
to Handle panic
Go
package main
import "fmt"
// recover function to handle panic
func handlePanic() {
// detect if panic occurs or not
a := recover()
if a != nil {
fmt.Println("RECOVER:", a)
}
}
func division(num1, num2 int) {
// execute the handlePanic even after panic occurs
defer handlePanic()
// if num2 is 0, program is terminated due to panic
if num2 == 0 {
panic("Cannot divide a number by zero")
} else {
result := num1 / num2
fmt.Println("Result:", result)
}
}
func main() {
division(4, 2)
division(8, 0) // This will cause a panic, but it will be recovered
division(2, 8)
}
Output:
Result: 2
RECOVER: Cannot divide a number by zero
Result: 0
In this example, the handlePanic
function is deferred inside the division
function. When a panic occurs, handlePanic
is called, and the program recovers from the panic instead of terminating.
Key Points About recover
- Deferred Execution:
recover
only works inside deferred functions. This ensures that it is called during the stack unwinding process after a panic. - Panic Message: The
recover
function returns the value passed to panic
, allowing you to log or handle the error message. - Graceful Recovery: Using
recover
allows your program to continue executing even after a critical error.
When to Use defer
, panic
, and recover
defer
: Use defer
for cleanup tasks, such as closing files, releasing locks, or logging. It ensures that resources are properly managed, even if an error occurs.panic
: Use panic
for unrecoverable errors, such as invalid input or system failures, where continuing execution would cause more harm.recover
: Use recover
to handle panics gracefully, especially in long-running applications like servers, where crashing is not an option.
Conclusion
Go’s defer, panic, and recover help manage errors and resource cleanup effectively:
- Use defer for cleanup and releasing resources.
- Use panic for critical errors that should stop execution.
- Use recover to handle panics and prevent crashes.
By mastering these, you can write robust and maintainable Go programs.
Similar Reads
Go Tutorial Go or you say Golang is a procedural and statically typed programming language having the syntax similar to C programming language. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009 as an open-source programming language and mainly used in Google
2 min read
Overview
Go Programming Language (Introduction)Go is a procedural programming language. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009 as an open-source programming language. Programs are assembled by using packages, for efficient management of dependencies. This language also supports env
11 min read
How to Install Go on Windows?Prerequisite: Introduction to Go Programming Language Before, we start with the process of Installing Golang on our System. We must have first-hand knowledge of What the Go Language is and what it actually does? Go is an open-source and statically typed programming language developed in 2007 by Robe
3 min read
How to Install Golang on MacOS?Before, we start with the process of Installing Golang on our System. We must have first-hand knowledge of What the Go Language is and what it actually does? Go is an open-source and statically typed programming language developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but
4 min read
Hello World in GolangHello, World! is the first basic program in any programming language. Letâs write the first program in the Go Language using the following steps:First of all open Go compiler. In Go language, the program is saved with .go extension and it is a UTF-8 text file.Now, first add the package main in your
3 min read
Fundamentals
Identifiers in Go LanguageIn programming languages, identifiers are used for identification purposes. In other words, identifiers are the user-defined names of the program components. In the Go language, an identifier can be a variable name, function name, constant, statement label, package name, or type. Example: package ma
3 min read
Go KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as an identifier. Doing this will result in a compile-time error. Example: C // Go program to illustrate the // use of key
2 min read
Data Types in GoData types specify the type of data that a valid Go variable can hold. In Go language, the type is divided into four categories which are as follows: Basic type: Numbers, strings, and booleans come under this category.Aggregate type: Array and structs come under this category.Reference type: Pointer
7 min read
Go VariablesA typical program uses various values that may change during its execution. For Example, a program that performs some operations on the values entered by the user. The values entered by one user may differ from those entered by another user. Hence this makes it necessary to use variables as another
9 min read
Constants- Go LanguageAs the name CONSTANTS suggests, it means fixed. In programming languages also it is same i.e., once the value of constant is defined, it cannot be modified further. There can be any basic data type of constants like an integer constant, a floating constant, a character constant, or a string literal.
6 min read
Go OperatorsOperators are the foundation of any programming language. Thus the functionality of the Go language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In the Go language, operators Can be categorized based on their different functiona
9 min read
Control Statements
Functions & Methods
Functions in Go LanguageIn Go, functions are blocks of code that perform specific tasks, which can be reused throughout the program to save memory, improve readability, and save time. Functions may or may not return a value to the caller.Example:Gopackage main import "fmt" // multiply() multiplies two integers and returns
3 min read
Variadic Functions in GoVariadic functions in Go allow you to pass a variable number of arguments to a function. This feature is useful when you donât know beforehand how many arguments you will pass. A variadic function accepts multiple arguments of the same type and can be called with any number of arguments, including n
3 min read
Anonymous function in Go LanguageAn anonymous function is a function that doesnât have a name. It is useful when you want to create an inline function. In Go, an anonymous function can also form a closure. An anonymous function is also known as a function literal.ExampleGopackage main import "fmt" func main() { // Anonymous functio
2 min read
main and init function in GolangThe Go language reserve two functions for special purpose and the functions are main() and init() function.main() functionIn Go language, the main package is a special package which is used with the programs that are executable and this package contains main() function. The main() function is a spec
2 min read
What is Blank Identifier(underscore) in Golang?_(underscore) in Golang is known as the Blank Identifier. Identifiers are the user-defined name of the program components used for the identification purpose. Golang has a special feature to define and use the unused variable using Blank Identifier. Unused variables are those variables that are defi
3 min read
Defer Keyword in GolangIn Go language, defer statements delay the execution of the function or method or an anonymous method until the nearby functions returns. In other words, defer function or method call arguments evaluate instantly, but they don't execute until the nearby functions returns. You can create a deferred m
3 min read
Methods in GolangGo methods are like functions but with a key difference: they have a receiver argument, which allows access to the receiver's properties. The receiver can be a struct or non-struct type, but both must be in the same package. Methods cannot be created for types defined in other packages, including bu
3 min read
Structure
Arrays
Slices
Slices in GolangSlices in Go are a flexible and efficient way to represent arrays, and they are often used in place of arrays because of their dynamic size and added features. A slice is a reference to a portion of an array. It's a data structure that describes a portion of an array by specifying the starting index
14 min read
Slice Composite Literal in GoThere are two terms i.e. Slice and Composite Literal. Slice is a composite data type similar to an array which is used to hold the elements of the same data type. The main difference between array and slice is that slice can vary in size dynamically but not an array. Composite literals are used to c
3 min read
How to sort a slice of ints in Golang?In Go, slices provide a flexible way to manage sequences of elements. To sort a slice of ints, the sort package offers a few straightforward functions. In this article we will learn How to Sort a Slice of Ints in Golang.ExampleGopackage main import ( "fmt" "sort" ) func main() { intSlice := []int{42
2 min read
How to trim a slice of bytes in Golang?In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you ar
3 min read
How to split a slice of bytes in Golang?In Golang, you can split a slice of bytes into multiple parts using the bytes.Split function. This is useful when dealing with data like encoded strings, file contents, or byte streams that must be divided by a specific delimiter.Examplepackage mainimport ( "bytes" "fmt")func main() { // Initial byt
3 min read
Strings
Strings in GolangIn the Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where every character is represented by one or more bytes using UTF-8 Encoding. In other words, strings are the immutable chain of arbitrary bytes(including bytes
7 min read
How to Trim a String in Golang?In Go, strings are UTF-8 encoded sequences of variable-width characters, unlike some other languages like Java, python and C++. Go provides several functions within the strings package to trim characters from strings.In this article we will learn how to Trim a String in Golang.Examples := "@@Hello,
2 min read
How to Split a String in Golang?In Go language, strings differ from other languages like Java, C++, and Python. A string in Go is a sequence of variable-width characters, with each character represented by one or more bytes using UTF-8 encoding. In Go, you can split a string into a slice using several functions provided in the str
3 min read
Different ways to compare Strings in GolangIn Go, strings are immutable sequences of bytes encoded in UTF-8. You can compare them using comparison operators or the strings.Compare function. In this article,we will learn different ways to compare Strings in Golang.Examplepackage main import ( "fmt" "strings" ) func main() { s1 := "Hello" s2 :
2 min read
Pointers