[Go] defer & recover

Panic recovery is a mechanism in Go that allows a program to handle unexpected errors (panics) gracefully. 

package main

import (
	"fmt"
)

func mayPanic() {
	// This function simulates a situation that causes a panic.
	// For example, a division by zero.
	panic("a problem occurred")
}

func safeCall() {
	// Defer a function to recover from a panic.
	defer func() {
		if r := recover(); r != nil {
			// r contains whatever was passed to panic()
			fmt.Println("Recovered from panic:", r)
		}
	}()

	// Call a function that may cause a panic.
	mayPanic()

	// This line will only be executed if the panic was successfully recovered.
	fmt.Println("Function executed successfully.")
}

func main() {
	safeCall()

	// This line will be executed if the panic is recovered.
	fmt.Println("Main function execution continues after safeCall.")
}

 

posted @ 2024-02-06 03:24  Zhentiw  阅读(3)  评论(0编辑  收藏  举报