Example of GO language standard error handling mechanism error usage
- 2020-05-09 18:43:22
- OfStack
This article illustrates the use of the GO language standard error handling mechanism, error. Share with you for your reference. The specific analysis is as follows:
In Golang, error handling mechanism 1 is generally used when a function returns, which is the external interface, while exception handling mechanism panic-recover 1 is generally used inside a function.
Introduction to the error type
The error type is actually an abstraction of the error interface for the Error() method, which Golang USES for standard error handling.
type error interface {
Error() string
}
In the general case, if the function needs to return an error, error is used as the last of several return values (but this is not mandatory). Reference model:
func Foo(param int) (n int, err error) {
// ...
}
if n, err := Foo(0); err != nil {
// Error handling
}
This is how to use error, which is easier and more intuitive than exceptions in other languages.
Code 1: classic usage
package main
import (
"errors"
"fmt"
)
func requireDual(n int) (int, error) {
if n&1 == 1 {
return -1, errors.New(" You did not enter an even number ") // generate 1 A simple error type
}
return n, nil
}
func main() {
if result, err := requireDual(101); err != nil {
fmt.Println(" Error: ", err)
} else {
fmt.Println(" Results: ", result)
}
}
Output results:
Error: you did not enter an even number
Have you ever found the error handling mechanism of Golang to be very simple?
Code 2: expand the above code to error output with custom parameters
package main
import (
"fmt"
)
type dualError struct {
Num int
problem string
}
func (e dualError) Error() string {
return fmt.Sprintf(" The parameter is incorrect because \"%d\" Not the number ", e.Num)
}
func requireDual(n int) (int, error) {
if n&1 == 1 {
return -1, dualError{Num: n}
}
return n, nil
}
func main() {
if result, err := requireDual(101); err != nil {
fmt.Println(" Error: ", err)
} else {
fmt.Println(" Results: ", result)
}
}
The output
Error: incorrect parameter because "101" is not an even number
I hope this article has helped you with your GO language programming.