banner
音小董

哩哔哩哔

这世上的热闹出自孤单

Chapter 6: Error Handling in Go Language

defer+recover Mechanism for Handling Errors#

In Go, we pursue elegant code and introduce the mechanism: defer+recover to capture and handle errors

package main  
  
import "fmt"  
  
func main() {  
test()  
fmt.Println("The division operation above executed successfully")  
fmt.Println("Executing the following logic normally")  
}  
func test() {  
defer func() {  
// Calling the recover built-in function can capture errors:  
err := recover()  
// If no error is captured, the return value is the zero value: nil  
if err != nil {  
fmt.Println("Error has been captured")  
fmt.Println("The error is:", err)  
}  
}()  
num1 := 10  
num2 := 0  
result := num1 / num2  
fmt.Println(result)  
}

Output:

Error has been captured
The error is: runtime error: integer divide by zero
The division operation above executed successfully                        
Executing the following logic normally   

Custom Error#

To create a custom error, you need to call the New function in the errors package: returns an error type
If the program encounters an error and wants to interrupt and exit the program: use the panic function in the builtin package

package main  
  
import (  
"errors"  
"fmt"  
)  
  
func main() {  
e := test2()  
panic(e) // If an error occurs, it will interrupt and exit the program  
fmt.Println("The division operation above finished executing")  
fmt.Println("Executing the following logic normally")  
}  
func test2() (err error) {  
num1 := 10  
num2 := 0  
if num2 == 0 { // If num2 is 0, return an error  
return errors.New("Program encountered an error, divisor cannot be 0") // The New function here returns an error type  
} else { // If num2 is not 0, execute normally  
result := num1 / num2  
fmt.Println(result)  
return nil  
}  
}

Output:

panic: Program encountered an error, divisor cannot be 0                 
                                                 
goroutine 1 [running]:                           
main.main()                                      
        E:/Golang/demo/错误处理/test2.go:10 +0x27
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.