banner
音小董

哩哔哩哔

这世上的热闹出自孤单

第6章:Go語言錯誤處理

defer+recover mechanism for error handling#

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

package main  
  
import "fmt"  
  
func main() {  
test()  
fmt.Println("Division operation above executed successfully")  
fmt.Println("Executing the following logic normally")  
}  
func test() {  
defer func() {  
// Call the built-in recover function to 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)  
}

Result of execution:

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

Custom error handling#

To create custom errors, 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("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  
}  
}

Result of execution:

panic: Program encountered an error, divisor cannot be 0                 
                                                 
goroutine 1 [running]:                           
main.main()                                      
        E:/Golang/demo/Error Handling/test2.go:10 +0x27
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。