This is a creation in Article, where the information may have evolved or changed.
Directory
-
- Defer and exception handling
- Overview
- Defer
- Define multiple Defer
- Change the return value
- Panic and recover
- Using panic
- Using recover
Summary
Defer,defer stack, change the return value, Panic,recover
Defer and exception handling
Overview
- Go does not have
try..catch
this anomaly mechanism, but uses panic
and recover
.
panic
Can be executed anywhere, recover
only in the function that is defer
called.
Defer
defer
Used to define statements executed at the end of a function execution
- Multiple
defer
will be formed defer 栈
, and later defined defer
statements will be called first
- Even if the function has a critical error, it will execute
- You can modify the result after a return by cooperating with the anonymous function
Define multiple Defer
func testDefer() { fmt.Println("a") defer fmt.Println("b") defer fmt.Println("c") deferfunc() { fmt.Println("d") //a d c b
Change the return value
Since defer executes at the end of the function execution, it can be used to change the value of the named return value
Incorrect use of
funcintint { deferfunc() { //返回的值,改变变量没有用 }() return x}x = changeResult(8)fmt.Println("x"//x 8
The right usage
funcintint) { deferfunc() { result++ }() return x}x = changeResult2(8)fmt.Println("x"//x 9
Panic and recover
panic
Used to pass an exception up, defer
followed by a very severe non-recoverable exception that causes the program to hang
recover
Can be panic
captured to make it panic
stop passing up
Using panic
func one() { fmt.Println("func one") }func two() { fmt.Println("func two") }func broken() { one() panic("func broken with Panic") two()}broken()
Output
func onepanicfunc broken with Panic异常消息...程序中断
Using recover
func one() { fmt.Println("func one") }func two() { fmt.Println("func two") }func catch() { one() deferfunc() { ifrecovernil { fmt.Println("func catch with Recover") } }() panic("func broken with Panic") two()}catch()
Output
func onefunc catch with Recover
Attention
defer
Need to be placed panic
before the definition
recover
After that, the logic does not revert to panic
that point, and the function will defer
return after