I'd like to argue that to a great degree, we can already do error handling the way the proposal demonstrates it in the 'corrected' new example through the tools we already have without introducing new keywords or new magic.
The following achieves the same error handling in almost exactly the same way without being much longer or uglier than the reference material.
func CopyFile(src, dst string) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("copy %s %s: %v", src, dst, err)
}
}()
r, err := os.Open(src)
if err != nil {
return err
}
defer r.Close()
w, err := os.Create(dst)
if err != nil {
return err
}
defer func() {
if err != nil {
w.Close()
os.Remove(dst) // (only if a check fails)
}
}()
if _, err := io.Copy(w, r); err != nil {
return err
}
return w.Close()
}
The proposal implies there is some gain in using handle over defer besides avoiding the repetitive
if err != nil { ... }
.If removing the repetitive
if err != nil { ... }
syntax is it's only purpose it should state it clearly and remove the misleading examples.