Go by Example: Recover

The recover function is used in conjunction with the panic function to handle run-time errors in Go. The panic function is used to raise a run-time error, while recover is used to handle the error and recover from it.

Here’s an example of using panic and recover:

package main

import (
	"fmt"
)

func divide(a, b int) int {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("Error:", r)
		}
	}()
	return a / b
}

func main() {
	result := divide(10, 2)
	fmt.Println("Result:", result)

	result = divide(10, 0)
	fmt.Println("Result:", result)
}

In this example, the divide function takes two integer arguments and returns their division. If the division results in a run-time error, such as dividing by zero, a panic will occur. The defer statement in the divide function is used to register a function that will be called when the divide function returns. The registered function uses the recover function to recover from a panic, printing a message indicating the error that caused the panic.

When the program is executed, the divide function is called twice, first with arguments 10 and 2, and then with arguments 10 and 0. When the divide function is called with arguments 10 and 0, a run-time error occurs and a panic is raised. The defer function registered in the divide function is called, and the recover function is used to recover from the panic. The error message is printed, indicating that a run-time error occurred. The program then continues to execute, allowing the user to take appropriate action in response to the error.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *