Golang delay function Defer as final processing file or exception
The defer function is advanced after the principle, when used inside the function, will be executed after the return, so according to this feature, you can handle because the exception causes the file stream not to close the problem (memory leak) and exception capture use, as follows:
- File stream shutdown
func CopyFile(dstName, srcName string) (written int64, err error) {src, err := os.Open(srcName)if err != nil {return}defer src.Close() // 此处就算后续因为异常return,也会执行此处的close()dst, err := os.Create(dstName)if err != nil {return}defer dst.Close()return io.Copy(dst, src)}
- Database query shutdown
resultIterator, err := stub.GetStateByPartialCompositeKey(DT_AGENT_COMMISSION_DATA,[]string{params.Agent_code,params.Period}) if err != nil { return ErrorPbResponse(RESP_CODE_SYSTEM_ERROR,err.Error()) } defer resultIterator.Close() //此处就算return或异常都会执行
- Used as an exception catch, combined with recover () to catch exception functions, similar to Java's final
func Test () {var exception interface{} temp ("Hello", func (E interface{}) {exception = e}) If exception! = nil {fmt. Println (Exception)} Return}func Temp (msg string, handler func (E interface{})) {defer func () {if err: = R Ecover (); Err! = Nil {handler (ERR)}} () Fmt. Println (Msg[len (msg) +1])//exception Return}func main () {test ()}