[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 @   Zhentiw  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2023-02-06 [Typescript] Global Scope
2023-02-06 [Typescript] Indexing an Object with Branded Types
2019-02-06 [TypeScript] Type Definitions and Modules
2019-02-06 [Tools] Add a Dynamic Tweet Button to a Webpage
2019-02-06 [Algorithm] Find Nth smallest value from Array
2018-02-06 [Javascript] Delegate JavaScript (ES6) generator iteration control
2017-02-06 [React] Use React.cloneElement to Extend Functionality of Children Components
点击右上角即可分享
微信分享提示