1
0

More than 3 years have passed since last update.

go修行8日目 Panicとか

Posted at

エラーハンドリング


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?
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0