Preface
First of all, let me say: The error refers to a problem that may occur. If the opening fails, this situation is expected. An exception refers to a problem that should not occur. If a null pointer is referenced, this situation is unexpected
Go
Provide two error handling methods
- Function return
error
Type object judgment error -
panic
Exception
1. panic
Go's type system will catch many errors at compile time, but some errors can only be checked at runtime, such as array access out of bounds, null pointer references, etc. These runtime errors can cause painc exceptions.
Generally speaking,When a panic exception occurs, the program will interrupt the running and immediately execute the function (defer mechanism) that is delayed in the goroutine (which can be understood as a thread first).. The program then crashes and outputs log information. Log information includes panic value and stack trace information for function calls. panic value is usually some kind of error message. For each goroutine, there will be a function call stack trace information in the log information that is opposite to it, when panic occurs. Usually, we do not need to run the program again to locate the problem, and the log information has provided sufficient diagnostic basis. Therefore, when we fill out the problem report, we generally record the panic exception and log information together. Not all panic exceptions come from the runtime, and calling the built-in panic function directly will also raise a panic exception; the panic function accepts any value as a parameter. When certain scenarios that should not happen, we should call panic. Although Go's panic mechanism is similar to the exceptions in other languages, the applicable scenarios of panic are somewhat different.Since panic causes program crash, panic is generally used for serious errors, such as inconsistent logic within the program.
panic
Can be called manually, butGo
Officially advise not to use itpanic
, every exception should be usederror
Object capture. If the exception occurs but is not caught and restored,Go
The execution of the program will be terminated, even if the location of the exception occurs is not in the mainGoroutine
This will also happen in .
To sum up:
panic is a serious error mechanism that causes the program to terminate, andList of defer functions that may exist when the panic function is executed in reverse order, and then return the caller of the function.The built-in recover function can be used to capture panic and restore the normal execution process of the program, but the recover function is only valid if it is used internally in defer
also,whenpanic()
When the triggered downtime occurs,panic()
The following code will not be run, but inpanic()
The function has been run beforedefer
Statements will still work when the downtime occurs
2. recover
1. recover
It's aGo
The language's built-in function allows thegoroutine
Recover.
2. Used to control the panicking behavior of a goroutine, capture the panic, and thus affect the application's behavior.
3. General call suggestions
a). In the defer function, the panicking process of a gojroutine is terminated by recever, thereby restoring the execution of normal code
b). The error passed through panic can be obtained
Simply put: a panic exception can be thrown in go, and then the exception can be caught by recover in defer, and then handled normally.
4. During normal execution, callrecover
Will returnnil
And no other effect;
Note: Use recover to process panic directives, defer must be declared before panic, otherwise recover cannot capture panic when panic.
To sum upGo
The language does not have an exception system, and its usepanic
Triggering downtime is similar to throwing exceptions in other languages.recover
The downtime recovery mechanism corresponds to thetry/catch
Mechanism.
The relationship between panic and recover
The combination of panic and recover has the following characteristics:
There is panic or not recover, the program is down.
There is panic and recover, and the program will not crash. After executing the corresponding defer, exit the current function from the downtime point and continue to execute.
Note: In the defer function triggered by panic, you can continue to call panic and further throw the errors out until the overall program crashes. If you want to set the return value of the current function when catching an error, you can set the return value directly using the named return value method.
Example:
package main func test() { defer func() { if err := recover(); err != nil { // recover catches error. println(err.(string)) // Transform interface{} into a specific type. } }() panic("panic error!") // panic throws an error} func main() { test() }
3. error
Error handling in go is done in the form of a return value, either you ignore it, or you deal with it (the processing can also continue to return to the caller). For golang's design method, we will write a lot of if judgments in the code to make a decision.
For err, if it is nil, it means there is no error. If it is not nil, it means there is a problem with the program and the error needs to be handled.
Example:
func main() { conent,err:=("filepath") if err !=nil{ //Error handling }else { (string(conent)) } }
In addition, the error type is a built-in type of the Go language. When using it, you don’t need to import it specifically. It is essentially an interface.
type error interface{ Error() string //Error() is an error message that needs to be filled in every customized error object. It can be understood as a field Error}
Summarize
This is all about this article about panic and error in GoLang. For more information about panic and error in GoLang, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!