Implementation of exception handling mechanism similar to try catch in Golang

Source: Internet
Author: User
Tags finally block try catch
This is a creation in Article, where the information may have evolved or changed. This article is from:http://golang.so/

This article does not describe the use of panic/recover. Because Panic/recover is not recommended for practical use.
However, the programmatic approach to try catch finally is often used.

The code is as follows:

Package Main
  
Import (
"FMT"
"Runtime"
"OS"
)
  
//Try to open a file named Dummy.one
//For input. Return the error if it won ' t open.
func dummy1 () error {
f,err:= os. Open ("Dummy.one")
if (err!=nil) {
Return Err
} else {
f.close ()
return Nil
   }
}
  
//Try to open a file named Dummy.two
//For input. Return the error if it won ' t open.
func dummy2 () error {
f,err:= os. Open ("Dummy.two")
if (err!=nil) {
Return Err
} else {
f.close ()
return Nil
   }
}
  
//If The error value is not nil,
//Display the caller ' s filename and
//Calling Line-number. Then, display
//The Error object. Return true
//If the Err parameter was true.
//Otherwise, return false.
func Disperr (err error) bool {
if (err!=nil) {
_,file,line,_:=runtime. Caller (1)
FMT. fprintf (OS. Stderr, "File:%s\nline:%d\nerr:%v\n", File,line,err)
return True
   }
return False
}
  
Func Main () {
var err error
  
//Create an anonymous function and
//Invoke it.
      //
//Use conditional returns to drop out
//Of the function block to simulate falling
//out of a "try" block.
      //
(func () {
FMT. Println ("attempt #1")
err=dummy1 ()
if Disperr (err) {return}
  
FMT. Println ("attempt #2")
err=dummy2 ()
if Disperr (err) {return}
   })()
  
if (err!=nil) {
//Catch block equivalent
FMT. Println ("In ' Catch ' Block")
   }
//Finally block equivalent
FMT. Println ("done!")
}

For details, please read the original text:Http://golang.so/thread-18-1-1.html
Related Article

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.