1
0

More than 3 years have passed since last update.

眺めて覚えるGo言語 その10 panic

Posted at

Go言語のpanicを知ってパニクッタのである。

なんかエラーがあって継続するのに難しいときに使うのがpanicです。

f9.go
package main

import (
    "fmt"
)

func main() {
    defer fmt.Println("パニクリました。")
    fmt.Println("Start")
    panic("パニックになりました")
}
実行結果
>go run f9.go
Start
パニクリました
panic: パニックになりました

goroutine 1 [running]:
main.main()
        C:/Users/hirat/go-work/function/f9.go:10 +0x12b
exit status 2

上記のようにdeferと共に使うとプログラムの中断がうまく行く。

f10.go
package main

import (
    "fmt"
)

func helloworld() {
    defer fmt.Println("End")
    fmt.Println("Start")
    panic("Panic!")
}


func main() {
    helloworld()
}

実行結果
>go run f10.go
Start
End
panic: Panic!

goroutine 1 [running]:
main.helloworld()
        C:/Users/hirat/go-work/function/f10.go:10 +0x12b
main.main()
        C:/Users/hirat/go-work/function/f10.go:15 +0x27
exit status 2

関数の中でパニクッても大丈夫。

難しい言い方するとスタックポインターをちゃんと戻す。

  • メモリーリークが起きない。
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