Golang delay function Defer as final processing file or exception

Source: Internet
Author: User

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:

    1. 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)}
    1. 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或异常都会执行
    1. 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 ()}  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.