Go Error Handling

main Package 
Import ( 
	"FMT" 
	_ "Time" 
) 

FUNC Test () { 
	// use defer + recover to capture and handle exceptions 
	the defer FUNC () { 
		ERR: = Recover () // Recover () built-in function, can capture abnormal 
		if err! = nil {// instructions to capture error 
			fmt.Println ( "ERR =", ERR) 
			// here you can send the wrong message to the administrator .... 
			fmt.Println ( "send mail to admin @ ~ sohu.com ") 
		} 
	} () 
	num1: 10 = 
	num2: = 0 
	RES: = num1 / num2 
	fmt.Println (" RES = ", RES) 
} 


FUNC main () { 

	// test 
	// test () 
	/ / for { 
	// fmt.Println ( "main () code below ...") 
	// time.sleep (time.Second) 
	//} 

} 

Custom Error Handling

main Package Penalty for 
Import ( 
	"fmt" 
	_ "Time" 
	"errors" 
) 

// function to read information in a profile of init.conf 
// If the file name passed is not correct, we will return a custom error 
func readConf ( String name) (ERR error) { 
	IF name == "the config.ini" { 
		// read ... 
		return nil 
	} the else { 
		// return a custom error 
		return errors.New ( "error reading file .." ) 
	} 
} 

FUNC Test02 () { 

	ERR: = readConf ( "config2.ini") 
	! = nil IF ERR { 
		// If the read file transmission errors, outputs the error, and terminates the program 
		panic (ERR) 
	} 
	fmt.Println ( "test02 () to continue ....") 
} 
	

FUNC main () { 
	// test custom error using 
	Test02 () 
	fmt.Println ( "main () code below ...") 
}

  

Guess you like

Origin www.cnblogs.com/yzg-14/p/12227460.html