Go Language Bible-panic anomalies
1. When the panic exception occurs, the program interrupts the operation and immediately executes the function that is delayed in the goroutine (defer mechanism)
2. Not all panic exceptions come from the runtime, and calling the built-in panic function directly also throws a panic exception; the panic function accepts any value as a parameter.
3. Since panic can cause a program to crash, panic is generally used for critical errors, such as inconsistent logic within the program, and for most vulnerabilities we should use the error mechanism provided by go instead of panic
4. To facilitate the diagnosis, the runtime package allows the output of stack information
Go language Bible-recover catch exception
1. In general, there should be no handling of panic exceptions, but sometimes we can recover from exceptions, at least we can do something before the program crashes.
2. A safe approach is selective recover
3. The built-in function recover is called in the deferred function, and the function defining the defer statement has a panic exception, recover causes the program to recover from panic and returns panic value. The function that caused the panic exception will not continue, but will return normally
Package Mainimport ( "FMT")/* Exercise 5.19: Use panic and recover to write a function that does not contain a return statement but can return a value other than 0. */func Main () { fmt. Println (Recovertest (20))//Return to 20}/*1. Originally only defined return type, now give the return value an appropriate name, directly using the internal anonymous function to modify the value 2. Using the defer mechanism, the function calls behind defer are deferred, 3 is called after encountering Pannic. Using closures, the function internally uses an anonymous function to access the variable 4 of the external function. Pannic exception */func recovertest (x int) (result int) is captured using recover mechanism { defer Func () { recover () result=x } () Panic (x)}
Go Language Bible-panic anomaly, recover catch exception exercises