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 main
import "fmt"
func main() {
result := safeDivide(10, 0) // This will trigger a panic
fmt.Println("Result:", result)
}
func safeDivide(a, b int) (result int) {
defer func() {
if r := recover(); r != nil {
// Handle the panic here
result = 0 // Assign a default value to result
fmt.Println("Panic recovered:", r)
}
}()
if b == 0 {
panic("Division by zero") // This line will trigger a panic
}
result = a / b
return 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 main package. In Go, a package is a way to organize and group related code together.

  • Line 3: This line imports the fmt package, which provides functions for formatting and printing text. It allows you to use functions like fmt.Println() to output text to the console.

  • Line 5: This is the main function, the entry point of your program. It's where out program starts executing.

  • Line 6: Here, we're calling the safeDivide function with the arguments 10 and 0. This function call will eventually lead to a panic due to division by zero.

  • Line 7: This line prints the result of the safeDivide function call. However, due to the panic and subsequent recovery, the value of result will be 0.

  • Line 10: This is the safeDivide function definition. It takes two integer arguments a and b and returns an integer result.

  • Line 11: This line uses the defer keyword to schedule an anonymous function to run when the safeDivide function 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 variable r. 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 result to a value of 0. This is a precautionary measure to have a safe and sensible value in case of a panic.

  • Line 19: This if statement checks whether the value of b is zero.

  • Line 20: If b is indeed zero, this line triggers a panic with the error message Division by zero.

  • Line 23: If no panic occurred, this line calculates the division of a by b and assigns the result to the result variable.

  • Line 24 : Finally, if no panic occurred, this line returns the calculated result.

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

Copyright ©2025 Educative, Inc. All rights reserved