0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Golang】パニック、リカバー

Posted at

【Golang】パニック、リカバー

Golangの基礎学習〜Webアプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。

package main
//パニック(例外)、リカバリー(復帰)
//パニックより推奨されているのは、エラーハンドリング
//強制的に終了する強力な機能な為、あえて使わない方がいい

import (
	"fmt"
)

//外部DB接続をイメージ
func thirdPartyConnectDB() {
	//パニックを起こす。例外を発生させる。
	panic("Unable to connect database!")
}

func save() {
	//deferを先に書く
	defer func() {
		//リカバリー システム終了をキャッチして復帰させる。
		s := recover()
		fmt.Println(s)
	}()
	thirdPartyConnectDB()
}

func main(){
    save()
	fmt.Println("リカバーしているので表示される")
}
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?