Home > Backend Development > Golang > Go Panic Recovery: Deferring `recover()` – What's the Difference?

Go Panic Recovery: Deferring `recover()` – What's the Difference?

Patricia Arquette
Release: 2024-12-03 03:35:11
Original
552 people have browsed it

Go Panic Recovery: Deferring `recover()` – What's the Difference?

Deferring recover() vs. defer recover()

In Go, a panic can be caught and handled using the recover() function. However, it's important to note that the placement of defer relative to the recover() call has significant implications.

Scenario A: defer func() { recover() }()

In this scenario, the defer statement schedules an anonymous function to be executed at the end of the current function. When this function is executed, it invokes the recover() function. This is an effective way to catch and handle panics because the recover() function will be executed even if a panic occurs before the enclosing function resumes execution.

Scenario B: defer recover()

In this scenario, the recover() function itself is scheduled as a deferred function. However, this doesn't work as intended because recover() doesn't call itself. Therefore, any panics that occur before the enclosing function resumes execution will not be caught by this deferred call.

This behavior is documented in the Go documentation: "If recover is called outside the deferred function it will not stop a panicking sequence."

An Interesting Example: defer (func() { recover() })()

To illustrate this further, consider the following code:

var recover = func() { recover() }
defer recover()
panic("panic")
Copy after login

Surprisingly, this code also doesn't panic. In this case, we create a recover variable of function type and initialize it to an anonymous function that calls the built-in recover(). We then specify the value of the recover variable as the deferred function. This allows us to catch and handle the panic because the deferred function effectively calls recover(), stopping the panicking sequence.

The above is the detailed content of Go Panic Recovery: Deferring `recover()` – What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template