This example describes the error usage of the Go language standard error handling mechanism. Share to everyone for your reference. The specific analysis is as follows:
In Golang, the error handling mechanism is usually used when the function returns, and it is the external interface, and the exception handling mechanism panic-recover generally used in the function.
Error type Introduction
The error type is actually an error interface that abstracts the error () method, Golang using the interface for standard error handling.
Copy Code code as follows:
Type Error Interface {
Error () string
}
In general, if the function needs to return an error, the error is the last of the multiple return values (but this is not a mandatory requirement). Reference Model:
Copy Code code as follows:
Func Foo (param int) (n int, err error) {
// ...
}
If n, err: = Foo (0); Err!= Nil {
Error handling
}
This is the use of error, compared with other languages of the exception, Golang method is relatively easier and more intuitive.
Code 1: The Classic use method
Copy Code code as follows:
Package Main
Import (
"Errors"
"FMT"
)
Func requiredual (n int) (int, error) {
If n&1 = 1 {
Return-1, errors. New ("You enter not double")//Generate 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 have entered a not-numbered
Do you feel that the golang of this kind of error processing mechanism is very concise ah, hehe!
Code 2: Expand the code above, error output with custom parameters
Copy Code code as follows:
Package Main
Import (
"FMT"
)
Type Dualerror struct {
Num int
Problem string
}
Func (e dualerror) Error () string {
Return FMT. Sprintf ("Incorrect parameter because \%d\" is not a double), 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)
}
}
Output results
Error: Incorrect parameter because "101" is not a double
I hope this article will help you with your go language program.