This article has included programming study notes . Covers PHP, JavaScript, Linux, Golang, MySQL, Redis, open source tools and more.
mistake
misunderstanding
In Go, an error is a state that represents a program error. Contains information about the state of the program at runtime and compile time. Generally, when we write Go code, we will encounter the following processing methods.
file, err := os.Create("test.txt")
fmt.Println(file)
if err != nil {
fmt.Println(err)
return
}
We use the os library to create a file named test.txt, the method returns a file pointer or err error message.
err indicates the error message when the file creation fails. When there is an error in storage, we do error handling to the program; when there is no error, other logic codes are executed normally.
custom error
Go allows us to customize error messages. Custom error messages need to use the New() function in the built-in error report. The following sample code:
package main
import (
"errors"
"fmt"
)
func printError() (a int, err error) {
err = errors.New("打印错误信息")
a = 1
return
}
func main() {
i, err := printError()
fmt.Println("i value is", i)
if err != nil {
fmt.Println(err)
return
}
}
Specific print information: i value is 1 打印错误信息
.
Implementation principle
When using the errors.New()
function, the package declares a structure errorString
and implements the method in the error interface body Error()
.
// errors包
package errors
func New(text string) error {
return &errorString{text}
}
type errorString struct {
s string
}
func (e *errorString) Error() string {
return e.s
}
// error接口
type error interface {
Error() string
}
abnormal
Cognitive anomalies
An exception is an exception message that occurs in a program in 编译时
or 运行时
. If the exception is not handled, it may cause the program to terminate the program or throw an exception message, causing the program to fail to run normally. Exceptions need to be handled strictly when the program is compiled or run. The following code, the program will trigger an exception when compiling, resulting in failure to compile normally:
package main
import "fmt"
func main() {
panic("print panic")
fmt.Println("end")
}
print result
╰─ go run demo6.go
panic: print panic
goroutine 1 [running]:
main.main()
/usr/local/var/www/go/golang_code/src/syntax/err/demo6.go:20 +0x39
exit status 2
- The Go runtime will trigger a runtime panic, which throws a value of the runtime.Error interface type along with the program crash. This error value has a RuntimeError() method to distinguish it from normal errors.
- Panic can be initialized directly from code: when the error condition (the code we are testing) is so severe and unrecoverable that the program cannot continue, the panic function can be used to generate a runtime error that aborts the program.
- panic takes an argument of any type, usually a string, which is printed when the program dies. The Go runtime is responsible for aborting the program and giving out debugging information.
- Call panic in a multi-level nested function call to immediately abort the execution of the current function.
Handling exceptions
When the program runs abnormally, it will terminate the normal operation of the program. Exception information needs to be handled strictly. In Go, recover() can be used to obtain exception information from panic and obtain the execution right of the program.
- As the name suggests, the (recover) built-in function is used to recover from panic or error scenarios: to allow the program to regain control from panicking, stop the termination process and resume normal execution.
- recover
只能
in defer-modified functions: used to obtain the error value passed in the panic call. If it is executed normally, calling recover will return nil, and has no other effect. - A panic will cause the stack to unwind until the defer-decorated recover() is called or the program aborts.
- All defer statements are guaranteed to execute and return control to the caller of the function that received the panic. This bubbles up to the very top, executes the defer (for each level), crashes the program at the top of the stack, and reports the error condition on the command line with the value passed to panic: this termination process is panicking.
Exception Handling Principles
- Inside the package, it should be recovered from the panic: explicit panic() out of package scope is not allowed. Inside a package, especially when there are deeply nested calls in non-exported functions, it is useful for calling functions to panic for error scenarios that should be translated into errors (and improve code readability). sex).
- Outside the package, return an error value (instead of panic) to the caller of the package.
- The principle of the Go library is that even if panic is used inside a package, it must be handled with recover in its external interface (API) to return an explicit error.
Exception Handling Practices
The following sample code triggers a panic() in the called function printPanic(), uses defer in the main() function to receive panic() information, and handles exceptions to panic().
package main
import "fmt"
func printPanic() {
panic("panic exception")
}
func main() {
defer func() {
err := recover()
if err != nil {
fmt.Println("panic is", err)
}
}()
printPanic()
fmt.Println("end")
}
print result
╰─ go run demo5.go
i value is 1
打印错误信息
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。