Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What are the error handling of Go language?

Shulou Source: shulou.com Published: 2022-06-02 02:17:30 09月17日 Update

This article shows you what the error handling of Go language has, the content is concise and easy to understand, it will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Learning goal

Master error handling

Master custom error handling

Master the use of defer keyword

Error handling

GO has no exception handling mechanism.

The Go language introduces a standard mode for error handling, the error interface, which is defined as follows: type error interface {

Error () string

}

You can quickly create error instances through errors.New

The code for errors.New ("error message") func Foo (param int) (n int, err error) {/ /...} / calls suggests handling the error situation as follows: n, err: = Foo (0) if err! = nil {/ / error handling} else {/ / use the return value n} Custom error Type defer keyword func CopyFile (dst, src string) (w int64) Err error) {srcFile, err: = os.Open (src) if err! = nil {return} defer srcFile.Close () dstFile, err: = os.Create (dstName) if err! = nil {return} defer dstFile.Close () return io.Copy (dstFile, srcFile)}

Similar to finally in Java

There can be multiple defer statements in a function

The invocation of the defer statement follows the principle of first in and then out, that is, the last defer statement will be executed first.

Painc and recover

Panic is used for unrecoverable errors

Panic executes the content specified by defer before exiting.

Error recovery

Defer func () {if err: = recover (); err! = nil {/ / restore error} ()

Os.Exit exit

The os.Exit direct termination program will not call the function specified by defer.

The current call stack information is not output when os.Exit exits.

What are the above contents of error handling in Go language? have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Tags: Error processing language content statement information key keyword function skill interface knowledge concise concise code advanced principle can be passed multiple instance Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple MariaDB Docker Xiaomi Microsoft