Go error handling
The Go language provides a very simple error handling mechanism through the built-in error interface.
The error type is an interface type, which is its definition:
type Interface { Errorstring}
We can generate error messages in the code by implementing the error interface type.
The function usually returns an error message in the final return value. Use errors. New can return an error message:
func Sqrt (f float64) (float64error) { if0 { return 0, errors. New ("math:square root of negativenumber") } // other logical implementations }
In the following example, we pass a negative number when we call Sqrt, and then we get the Non-nil Error object, comparing this object to nil, and the result is true, so fmt. PRINTLN (The FMT package calls the error method when handling error) is called to output an error, see the sample code called below:
Sqrt (-1) if err! = nil { fmt. PRINTLN (ERR)}
The concrete examples are as follows:
Package Mainimport"FMT"//Define a DIVIDEERROR structureType Divideerrorstruct{Divideeint //DivisorDividerint //Dividend}//bind the error method to Divideerror to implement the error interfaceFunc (de *divideerror) Error ()string { //Use the SLR quotes to make the input more attractive to the writing formatStrformat: =' cannot procceed, the divider is zero. Dividee:%d divider:0 'returnFMT. Sprintf (Strformat, De.dividee)}//functions that define the INT type division operationFunc Divide (Vardivideeint, Vardividerint) (Resultint, errormessagestring) { ifVardivider = =0 { //instantiation of a simple method struct bodyDData: =divideerror{Dividee:vardividee, Divider:vardivider,} errormessage= Ddata.error ()//call method to get corresponding error message return } Else { returnVardividee/vardivider,""}}func Main () {//Normal situation ifresult, ErrorMessage: = Divide ( -,6); ErrorMessage = =""{fmt. Println ("100/6 =", result)} //An error message is returned when the divisor is 0 if_, ErrorMessage: = Divide ( -,0); ErrorMessage! =""{fmt. Println ("errormessage is:", ErrorMessage)}}
Operation Result:
- 6 = : is zero. - 0
The error of Go_10:go Language Foundation