Keywords Introduction
panic
: Indicates the end and exit of the program. The language ofpanic
The keyword is used to actively throw exceptions, similarjava
And so on.throw
The keyword.recover
: Restores the program state from a serious error to normal. The language ofrecover
Keywords are mainly used to catch exceptions and return the program to normal state, similarjava
And so on.try ... catch
。
use
-
panic
- happen
panic
After, the subsequent code will not execute - happen
panic
After that, it will executedefer
The list
We create two coroutines and panic occurs in one of them. Let’s see what happens with the other coroutine.
package main import "fmt" func main(a) { // The first coroutine go func(a) { var i int for { i++ fmt.Println("Coroutines 1") time.Sleep(1*time.Second) // Panic occurs 3 seconds later if i==3 { panic("Abnormal exit")}}} ()// The second coroutine go func(a) { for { fmt.Println("Coroutines 2") time.Sleep(1*time.Second) } }() // let the main coroutine not exit for { time.Sleep(1*time.Second) } } Copy the code
Five seconds after the program is executed, one of the coroutines will panic(” abnormal exit “), the program will exit, and the other coroutine will terminate.
Output:
Coroutine 2 Coroutine 1 Coroutine 2 Coroutine 1 Coroutine 2 Coroutine 1 Coroutine 2 main.main.func1() /home/zheng/STUDY/GoWork/demo/main.go:28 +0xb9 created by main.main /home/zheng/STUDY/GoWork/demo/main.go:15 +0x35Copy the code
so
panic
If not, it can lead to the serious consequences of shutting down the entire program - happen
-
recovery
-
To solve panic problems, Go also provides a function called Recovery to catch exceptions and ensure that the program runs normally.
-
Valid only for panic that is currently occurring in Goroutine
-
Recovery will be used in conjunction with defer, because recovery will only be effective if it is executed after panic occurs, but subsequent code that panic occurs will not be executed, but defer will be executed
We add Recovery to the first coroutine of the above program
// The first coroutine go func(a) { // Catch an exception defer func(a) { err:=recover() fmt.Printf("Captured: %s\n",err) }() var i int for { i++ fmt.Println("Coroutines 1") time.Sleep(1*time.Second) // Panic occurs 3 seconds later if i==3 { panic("Abnormal exit")}}} ()Copy the code
Output:
coroutines2coroutines1coroutines1coroutines2coroutines2coroutines1coroutines2Caught: Exception exit coroutine2coroutines2.Copy the code
You can see that thread 1’s recovery catches the exception to panic for the current coroutine and outputs the cause of the exception. But the other coroutine 2 is going to continue.
-