How to return a value from function that panics in Go
In the Go programming language, the term panic refers to a runtime error that occurs when the program encounters an exceptional situation or a situation where it cannot continue executing safely. When a panic occurs, the program stops its normal execution and begins to unwind the stack of function calls, performing any necessary cleanup along the way.
You can read more about the
panic()method here.
However, if you want to capture information before panicking, you can use the built-in defer mechanism along with the recover() method. The recover() method is used to catch a panic and obtain the value that was passed to panic(). Here's an example of how you can achieve this:
package mainimport "fmt"func main() {result := safeDivide(10, 0) // This will trigger a panicfmt.Println("Result:", result)}func safeDivide(a, b int) (result int) {defer func() {if r := recover(); r != nil {// Handle the panic hereresult = 0 // Assign a default value to resultfmt.Println("Panic recovered:", r)}}()if b == 0 {panic("Division by zero") // This line will trigger a panic}result = a / breturn result}
Remember that using panics and recovers should be used judiciously and for truly exceptional situations. In most cases, it's better to handle errors gracefully using Go's built-in error handling mechanisms instead of relying on panics and recovers.
Code explanation
Line 1: This line indicates that we're defining the
mainpackage. In Go, a package is a way to organize and group related code together.Line 3: This line imports the
fmtpackage, which provides functions for formatting and printing text. It allows you to use functions likefmt.Println()to output text to the console.Line 5: This is the
mainfunction, the entry point of your program. It's where out program starts executing.Line 6: Here, we're calling the
safeDividefunction with the arguments10and0. This function call will eventually lead to a panic due to division by zero.Line 7: This line prints the result of the
safeDividefunction call. However, due to thepanicand subsequent recovery, the value ofresultwill be0.Line 10: This is the
safeDividefunction definition. It takes two integer argumentsaandband returns an integerresult.Line 11: This line uses the
deferkeyword to schedule an anonymous function to run when thesafeDividefunction exits. The anonymous function is used to handle panics and recover from them.Line 12: We're starting a conditional check here. We're using the
recover()function to capture any ongoing panic and assign its value to the variabler. This function helps us handle situations where the program might be in trouble.Line 14: Inside our emergency response, we're setting a variable called
resultto a value of0. This is a precautionary measure to have a safe and sensible value in case of a panic.Line 19: This
ifstatement checks whether the value ofbis zero.Line 20: If
bis indeed zero, this line triggers apanicwith the error messageDivision by zero.Line 23: If no
panicoccurred, this line calculates the division ofabyband assigns the result to theresultvariable.Line 24 : Finally, if no
panicoccurred, this line returns the calculatedresult.
Conclusion
The provided code snippet uses the recover() function to gracefully handle panics within a deferred function. If a panic occurs, it assigns a default value to a variable (result), prints a recovery message along with the panic value, and ensures the program continues without crashing. This approach creates a safety mechanism akin to an emergency response, helping to prevent abrupt failures and maintaining program stability.
Free Resources