1、创建错误
package main
import (
"errors"
"fmt"
)
func main() {
f := 0
fr, error := Sqrt(f)
if error != nil {
fmt.Println("error: ", error)
return
}
fmt.Println("result: ", fr)
}
func Sqrt(f int) (int, error) {
if f <= 0 {
return -1, errors.New("math - square root of negative number")
}
return f * f, nil
}
2、 恢复错误
package main
import (
"fmt"
)
func main() {
fmt.Printf("Calling test\r\n")
test()
fmt.Printf("Test completed\r\n")
}
func test() {
defer func() {
if e := recover(); e != nil {
fmt.Printf("Panicing %s\n", e)
}
}()
panic("bad end")
}
3、自定义错误处理
package main
import (
"fmt"
"strconv"
"strings"
)
// 定义错误类型
type ParseError struct {
Index int
Word string
Err error
}
// 定义错误输出
func (e *ParseError) String() string {
return fmt.Sprintf("解析错误: 第%d位无法将[%s]解析为int", e.Index, e.Word)
}
// 解析函数, 将string元组中每个字符转换成int并返回相应的int元组
func Parse(input string) (numbers []int, err error) {
defer func() {
// 以下相当于java的finaly
if r:= recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
// 转换错误语
err = fmt.Errorf("解析错误: %v", r)
}
}
}()
// 获取各组string
fields := strings.Fields(input)
numbers = fileds2numbers(fields)
return
}
// 将元组中的string逐个转成int
func fileds2numbers(fileds []string) (numbers []int) {
if len(fileds) == 0 {
panic("数组长度为0")
}
for idx, filed := range fileds {
num, err := strconv.Atoi(filed)
if err != nil {
// 此处相当于java的throw Exception
panic(&ParseError{idx, filed, err})
}
numbers = append(numbers, num)
}
return
}
func main() {
var strs = []string{
"1 2 3 4 ",
"5 6 7",
"2 + 2",
"",
}
for _, line := range strs {
fmt.Printf("开始解析 %q:\n ", line)
nums, err := Parse(line)
if err != nil {
fmt.Println(err) // here String() method from ParseError is used
continue
}
fmt.Printf("解析结果:%v \n", nums)
}
}
4、执行系统命令
package main
import (
"fmt"
"os"
)
func main() {
env := os.Environ()
procAttr := &os.ProcAttr{
Env: env,
Files: []*os.File{
os.Stdin,
os.Stdout,
os.Stderr,
},
}
pid, err := os.StartProcess("/bin/ls", []string{"ls", "-l"}, procAttr)
if err != nil {
fmt.Printf("Error %v starting process!", err)
os.Exit(1)
}
fmt.Printf("The process id is %v", pid)
}
网友评论