err ! = nil

Go has been criticized for its error handling, and it doesn’t have try and catch, and it’s really anti-human compared to other languages, so Go usually handles errors by comparing returned errors to nil. A nil value means that no error occurred, whereas a non-nil value means that an error occurred. So the following lines of code often appear:

iferr ! =nil {
        fmt.Println("error:",err)
        return
    }
Copy the code

If you want to implement a function and want to pass an error message to the caller, you define an error type in the return value of the function. This error type actually uses the error interface of the error () method. Any type that implements this interface can be considered an error type:

type error interface {  / / the error interface
    Error() string   / / the Error method
}
Copy the code

This error interface is used in many third-party package methods or built-in package methods. Here’s a practical example:

package main
import (
    "fmt"
    "strconv"
)

func main(a) {
    resp, err := strconv.Atoi("hello")  // Strconv is a built-in package for converting data types. The Atoi method converts a string to an int
    iferr ! =nil {
            fmt.Println(err) Strconv. Atoi: parsing "hello": invalid syntax
    }else{
            fmt.Println(resp)
    }
}
Copy the code

We can also use this method by writing our own code to pass an error message to the caller and let the caller determine if there is an error, as shown below:

package main
import (
	"fmt"
	"errors"
)

func ErrorMake(a,b int) (int,error){
	if b==0 {
		return 0,errors.New("B cannot be zero")}else {
		return a / b,nil}}func main(a) {
	var a,b=1.0
	resp,err := ErrorMake(a,b)
	iferr! =nil {
		fmt.Println(err)  //b cannot be zero
	}else {
		fmt.Println(resp)
	}
}
Copy the code

Panic and defer

The word panic means panic, and the function of Go is to actively throw an error. I often use Raise to actively throw an error when using Python, and then send the error to try Except to accept it.

try:
    a = input("Enter a number:")
    if(not a.isdigit()):
        raise ValueError("A must be a number.")
except ValueError as e:
    print("Throw an exception:".repr(e)) // Input something other than a number will automatically output an error message hereCopy the code

Panic? Examples of actively throwing errors:

package main
import "fmt"

func showpanic(data int){
    if data == 0{
        panic("The passed argument is zero. Not supported.")}else{ 
        fmt.Println(data)
    }
}


func main(a) {
    showpanic(1)  / / output 1
    showpanic(0)  // Actively throws an error passing the argument to zero. Does not support oh
}
Copy the code

Panic is a very serious error, which will cause the program to stop running. After the program stops running, it usually needs to cooperate with releasing some resources, such as closing files, closing network connections, and logging out, etc. In Go language, we often see that panic can be used to actively throw errors, which can be realized by using defer. What is defer? The defer keyword is used to modify a function or method that executes before it returns. Here’s a common point: Multiple deferred, executed in reverse order, stacks up. Let’s take a quick look at the example of defer:

package main
import "fmt"

func testdefer(data string)  (return_data string) {
    defer fmt.Println("666")
    return data+"10086"  
}

func main(a) {
    fmt.Println(testdefer("call "))}Copy the code

Output in turn:

Awesome!
call 10086
Copy the code

Defer executes before an error is thrown, and before a function or method return:

package main
import "fmt"

func login(password string)  (return_data string) {
    defer fmt.Println("666")
    return data+"10086"  
}

func main(a) {
    fmt.Println(testdefer("call "))}Copy the code

Panic is used with defer:

package main
import "fmt"

func login(password string)  (return_data string) {
    defer fmt.Println("Record")
    
    if (password=="123456") {return "Login successful"
    }else{
        panic ("Fatal error, GG.")}}func main(a) {
    fmt.Println(login("123456"))
    fmt.Println(login("654321"))}Copy the code

Output:

Record the login success recordspanic: Fatal error, GG....Copy the code

The use of the panic keyword is generally not recommended, because it indicates the termination of the program. Error is usually used, and the program will not be terminated if an error is thrown.