10, golang error handling, panic stops program execution with caution

main Package 

Import (
"errors"
"FMT"
"IO / ioutil"
)

type interface {error
Error () String
}

/ *
golang error handling, the error is a golang type, default error if no error occurred, return speak value is nil
IF ERR! = nil {
something Wentworth wrong
}
golang mistakes like any other type of error can be passed as a function of error between
panic stop immediately let golang program execution, be used with caution. Unless extreme cases the program will bring a lot of problems or error has occurred can not be processed

! IF ERR = nil {
panic (ERR)
}
golang language does not support try --catch - finally control structure
* /

FUNC main () {
var File [ ] byte
var ERR error
File, ERR = ioutil.ReadFile ( "foo.txt")
IF ERR! = nil {
fmt.Println ( "111")
fmt.Println (ERR)
return
}
fmt.Println (string (File)) // file is read out of a byte string type array [] byte, string needs to be converted to text

err1: = errors.New ( "Something Wrong Wentworth ")
! = nil {IF ERR1
fmt.Println (ERR1)
}
panic (" OH NO NO more.Goodby ICAN do ") // panic can cause the program to immediately stop the execution, caution

name, role: =" Richard Jupp "," Drummer "
ERR2: = fmt.Errorf (" of The% V,% vquit ", Role, name)
IF ERR2 = nil {!
fmt.Println (ERR2)
}


}

FUNC Half (numberToHalf int) (int, error) {
IF numberToHalf% 2! = 0 {
return -1, fmt.Errorf ( "Can Not Half% V", numberToHalf)
}
return numberToHalf / 2, nil
}

Guess you like

Origin www.cnblogs.com/iifeng/p/11488996.html