Home >Backend Development >Golang >Can golang panic capture standard error?
##panic Access out of bounds, null pointer reference, etc. These runtime errors will cause panic exceptions. There are no exception capture statements such as try...catch... in golang, but panic and recover built-in functions are provided for throwing exceptions and catching exceptions.
• The parameter type of panic and recover is interface{}, so any type of object can be thrown.• If a fatal error occurs in the program and the entire program cannot proceed, golang provides the panic function to exit the program.
• When a program panics, use recover to regain control of the program. • Not all panic exceptions come from runtime. Directly calling the built-in panic function will also cause a panic exception. • The panic function accepts any value as a parameter.(1) Use of panic
① Errors caused during delayed debugging can be captured by subsequent delayed debugging, but only the last error can be captured.func test() {defer func() { fmt.Println(recover()) }()defer func() { panic("defer panic") }() panic("test panic") }func main() { test() //defer panic}②When a function panics, it will terminate running. After all delay functions are executed, program control returns to the caller of the function. This process will continue until all functions of the current coroutine return and exit, then the program will print out panic information, then print out the stack trace, and finally the program will terminate. If the function does not panic, calling the recover function will not obtain any information and will not affect the current process.
demo
package mainimport ( "fmt")func fullName(firstName *string, lastName *string) { if firstName == nil { panic("Firsr Name can't be null") } if lastName == nil { panic("Last Name can't be null") } fmt.Printf("%s %s\n", *firstName, *lastName) fmt.Println("returned normally from fullName") }func test(){ defer fmt.Println("deferred call in test") firName := "paul" fullName(&firName, nil) }func main() { defer fmt.Println("deferred call in main") test() fmt.Println("returned normally from main") }
The above is the detailed content of Can golang panic capture standard error?. For more information, please follow other related articles on the PHP Chinese website!