panic

Panic is usually an unrecoverable error program

When Panic throws an exception, it prints out the program stack.

The program does not proceed to panic.

The call from Panic does not prevent the defer program from executing:

func TestPanic(t *testing.T) {
	defer func(a) {
		fmt.Println("finally")
	}()
	fmt.Println("start")
	panic(errors.New("Something wrong"))}Copy the code

Program output

=== RUN TestPanic start finally -- FAIL: TestPanic (0.00s) Panic: Something wrong Something wrong goroutine 6 [running]: Testing. The tRunner. Func1.2 ({0 x975600, 0xc000042530}) D:/Go/src/testing/testing.go:1209 +0x24e testing.tRunner.func1() D:/Go/src/testing/testing.go:1212 +0x218  panic({0x975600, 0xc000042530}) D:/Go/src/runtime/panic.go:1038 +0x215 command-line-arguments.TestPanic(0x0)Copy the code

The os.exit () push program will not run the specific functions of defer

func TestPanic(t *testing.T) {
	defer func(a) {
		fmt.Println("finally")
	}()
	fmt.Println("start")
	os.Exit(1)
	//panic(errors.New("Something wrong"))
}
Copy the code

The output

=== RUN   TestPanic
start
Copy the code

recover

Recover is used to prevent the process from crashing when the code performs panic. Using recover, the process can still run

func TestRecover(t *testing.T) {
	defer func(a) {
		if err := recover(a); err ! =nil {
			fmt.Println("Catch Error", err)
		}
	}()
	fmt.Println("start")
	panic(errors.New("this error"))}Copy the code

The output

=== RUN TestRecover start Catch Error This Error -- PASS: TestRecover (0.00s) PASSCopy the code

Although panic has been executed here, recover has been called to catch exceptions in defer after panic. This implementation is similar to the logic of try {} catch() {} in PHP or Java

However, the recover method is not recommended to use blindly:

If there is no corresponding application resource on the server, panic is executed and exceptions are thrown, but recover is used again for recovery. Some health check programs just check whether the process exists. This results in what is called a zombie process: the process is still alive, but there are no resources to execute the corresponding logic.

Therefore, when using Recover, we still need to think about it. We can’t use it blindly.