异常处理
package mainimport ("fmt""os"
)/*
go语言中尽量避免抛出异常
一般发生异常错误,都期望程序员自己处理
在函数的实现过程中,出现了不能处理的错误,可以返回给调用者处理
*/func main() {_, err := os.OpenFile("test.txt", os.O_RDONLY, 777)if err != nil {fmt.Println("打开文件失败")}
}
自定义错误
//自己产生错误类型
//内置类型 error
//产生错误的内置包 errorsfunc main() {if e := hello(""); e != nil {fmt.Println(e)}// hello("zhuhongye")
}func hello(name string) error {if len(name) == 0 {return errors.New("NameError: name is empty!!!!!")}fmt.Println("hello,", name)return nil
}
未知错误
package mainimport ("errors""fmt"
)/*
自定义的error 往往都是能够预知的
不能预知的 go-- panic --程序终止了
*/
func main() {num := getelem(3)fmt.Println(num)
}// 未预料错误
func getelem(index int) int {arr := [3]int{10, 20, 30}return arr[index]
}
尽量避免panic
package mainimport ("errors""fmt"
)func main() {if num, e := getelem(3); e != nil {fmt.Println(e)} else {fmt.Println(num)}
}func hello(name string) error {if len(name) == 0 {return errors.New("NameError: name is empty!!!!!")}fmt.Println("hello,", name)return nil
}// 未预料错误
func getelem(index int) (int, error) {arr := [3]int{10, 20, 30}//return arr[index]//尽量避免panicif -1 < index && index < len(arr) {return arr[index], nil}return 0, errors.New("index out of range")
}
recover() 函数
/*
recover() 函数 用于终止异常处理流程 类似于 try...except...
recover() 要配置defer执行
defer 延迟处理语句 -->先放进去的后执行
*/
package mainimport ("fmt"
)func main() {fmt.Println("this is defer test!")defer fmt.Println(100)defer fmt.Println(200)fmt.Println("this is defer test2...")getlem(3)
}func getlem(index int) int {defer func() {if r := recover(); r != nil {fmt.Println("something error!", r)}fmt.Println("defer 语句!")}() //不管有没有panic 在退出函数执行之前,defer语句都会执行arr := [3]int{5, 6, 7}panic("手动抛出异常")//类似于python里面的raisereturn arr[index]
}
文件操作
使用os打开
package mainimport ("bufio""fmt""io""os"
)/*
文件操作
打开文件 -- os.Open os.OpenFile
os.Open 只能以只读的方式打开文件
os.OpenFile 可以指定文件的打开方式,权限等
*/func main() {/*OpenFile 指定文件打开方式O_RDONLY 只读O_WRONLY 只写O_RDWR 读写*/file, e := os.OpenFile("test.txt", os.O_RDONLY, 777)if e != nil {fmt.Println("打开文件失败!")} else {//使用Read读取// data := make([]byte, 10)// for {// len, _ := file.Read(data)//每次读取到内容长度,就是data的大小,适用于大文件读取// if len == 0 {//长度为0,表示读取完成// break// }// fmt.Println("每次读取:", string(data))// }//使用bufio读取 方式灵活 可以指定按行读取或者按分隔符读取 速度相对慢一点reader := bufio.NewReader(file)//按行读取for {line, _, e := reader.ReadLine()if e == io.EOF { //读到行尾break}fmt.Println("按行读:", string(line))}file.Seek(0,0)//移动文件指针到最开始位置}file.Close() //关闭打开文件,释放占用内存资源
}
使用ioutil打开
package mainimport ("fmt""io/ioutil"
)func main() {//使用ioutil读取 速度快 一次性读完,适合小文件读取file3, _ := ioutil.ReadFile("test.txt")fmt.Println(string(file3))
}
写文件
//写文件 io.WriteString file.WriteString bufio.NewWriterfile, _ := os.OpenFile("test.txt", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777)n, _ := io.WriteString(file, "this is io.WriteString\n")fmt.Println("n是字节数:", n)file.WriteString("直接使用打开文件写入!\n")