Recover Panics With Typed Values
Turn panics into errors by recovering in a deferred function and switching on the panic value: runtime errors implement error, strings stay strings.
Code
package main
import "fmt"
func safeDivide(a, b int) (result int, failure error) {
// recover 只在 defer 函数里有效:把 panic 转成普通错误返回
defer func() {
r := recover()
if r == nil {
return
}
switch v := r.(type) {
case error:
// 除零 panic 的值是 runtime.Error,实现了 error 接口
failure = fmt.Errorf("recovered error: %w", v)
case string:
failure = fmt.Errorf("recovered string: %q", v)
default:
failure = fmt.Errorf("recovered %T: %v", r, r)
}
}()
result = a / b // b == 0 触发运行时 panic
return
}
func main() {
for _, pair := range [][2]int{{10, 2}, {6, 0}} {
result, failure := safeDivide(pair[0], pair[1])
if failure != nil {
fmt.Printf("%d/%d failed: %v
", pair[0], pair[1], failure)
continue
}
fmt.Printf("%d/%d = %d
", pair[0], pair[1], result)
}
}Following the call path
Recover Panics With Typed Values is built around the functions safeDivide and main.
Repetition is confined to for _, pair := range [][2]int{{10, 2}, {6, 0}} — the rest of the file is straight-line. Cleanup is attached with defer, so it runs on every exit path of the function.
Points of care
- The package manager has no part in this; each call lands on a built-in API.
Putting it to use
Signature: func safeDivide(a, b int) (result int, failure error)
Execute the file and main walks through safeDivide, in that order.
Core lines
failure = fmt.Errorf("recovered error: %w", v)
for _, pair := range [][2]int{{10, 2}, {6, 0}} {
result, failure := safeDivide(pair[0], pair[1])
if failure != nil {
fmt.Printf("%d/%d failed: %v
", pair[0], pair[1], failure)
continue
}
fmt.Printf("%d/%d = %d
", pair[0], pair[1], result)
}
failure = fmt.Errorf("recovered string: %q", v)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- How do you run Recover Panics With Typed Values?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.