[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.")
}
分类:
Go
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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