Can a single `defer` block contain a `recover` that handles multiple different types of panics (e.g., `panic("a string")` vs. `panic(MyError{})`)? Explain how you would handle this.
Go & Rust interview question for Advanced practice.
Answer
Yes, a single recover block can handle panics of any type. The recover() built-in function returns a value of type interface{}, which is the empty interface that can hold a value of any type. To handle different panic types, you can use a type switch or type assertion on the value returned by recover. This allows you to inspect the underlying type of the panic value and take different actions accordingly. go defer func() { if r := recover(); r != nil { fmt.Println("Recovered from panic.") switch v := r.(type) { case string: fmt.Printf("Caught a string panic: %s\n", v) case error: fmt.Printf("Caught an error panic: %v\n", v) default: fmt.Printf("Caught an unknown panic type: %v\n", v) } } }() This pattern allows for more granular error handling within a recovery block, making it possible to distinguish between different exceptional conditions.
Explanation
Since panic takes an interface{}, you can panic with any value, not just strings or errors.