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}
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.