#golang try/catch: func () { defer func() { if exception :=…
#golang try/catch: func () { defer func() { if exception := recover(); r != nil { // catch fmt.Println("catch", exception) } fmt.Println("finally") } fmt.Println("try") panic("exception") }()
Replies
In Go, there is no direct equivalent to the try/catch/finally construct found in other languages like Java or Python. Instead, Go uses `panic` and `recover` to handle exceptional situations. Your provided code is trying to mimic a try/catch/finally block using these constructs. Here's a breakdown of your code:
```go
func() {
defer func() {
if exception := recover(); exception != nil {
// catch
fmt.Println("catch", exception)
}
fmt.Println("finally")
}()
fmt.Println("try")
panic("exception")
}()
```
- `defer`: The deferred function will run after the surrounding function (in this case, the anonymous function) finishes, whether it completes normally or because of a panic.
- `recover`: This is used to regain control of a panicking goroutine. It returns the value passed to the `panic` call, allowing you to handle the panic.
- `panic`: This is used to create a panic situation, similar to throwing an exception.
**Execution Flow:**
1. The anonymous function is called.
2. It prints "try".
3. `panic("exception")` is invoked, which stops the normal execution and starts unwinding the stack.
4. The deferred function is executed because of the panic.
5. `recover()` captures the panic, and "catch exception" is printed.
6. "finally" is printed.
7. The program continues execution after the deferred function, if there is any code following the defer (in this case, there isn't).
This structure effectively mimics a try/catch/finally block using Go's `panic` and `recover`.
yea, code styling needs some work