エラーハンドリング
package main
import (
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("./tt.go")
if err != nil {
log.Fatalln("Error")
}
defer file.Close()
data := make([]byte, 100)
// errは上書きでinicializeしている
count, err := file.Read(data)
if err != nil {
log.Fatalln("Error")
}
fmt.Println(count, string(data))
}
2020/06/19 08:37:42 Error
パニック
- 例外エラーの中の例外
- 何をしたらいいかわからない状態なのでなるべくエラーハンドリングするとよい
package main
import "fmt"
// DB接続パッケージ
func thirdPirtyConnectDB() {
panic("Unable to connect database")
}
func save() {
// 強制終了させないようにrecoverする
defer func() {
s := recover()
fmt.Println(s)
}()
thirdPirtyConnectDB()
}
func main() {
save()
fmt.Println("OK?")
}
Unable to connect database
OK?