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
関数の中でパニクッても大丈夫。
難しい言い方するとスタックポインターをちゃんと戻す。
- メモリーリークが起きない。