Code Monkey home page Code Monkey logo

Comments (3)

ffhelicopter avatar ffhelicopter commented on June 14, 2024

不知能否具体举例说明,多谢了!

在这种条件语句中有可能执行不到defer:
func t(i int) int {
fmt.Println(i)
i++
if i > 0 {
return i
} else {
defer func() {
fmt.Println(i)
}()
return i
}

}

from go42.

xinxindu avatar xinxindu commented on June 14, 2024

因为自己踩过坑,所以贴出来,让大家注意一下,谢谢笔者总结。
例子:
`func TestDefer() {
fmt.Println("start")
panic("generate panic.")

defer func() {                // defer是无法执行的,导致recover是无效的 
	ret := recover()
	if ret != nil {
		fmt.Println("TestDefer panic")
	} else {
		fmt.Println("TestDefer has no panic")
	}
}()

}`

from go42.

ffhelicopter avatar ffhelicopter commented on June 14, 2024

多谢说明。这是因为在Go中规定:panic之前需要先声明好defer。


15.2 Panic

在Go语言中 panic 是一个内置函数,用来表示非常严重的不可恢复的错误。必须要先声明defer,否则不能捕获到panic异常。

from go42.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.