GO: Panic, Recover

GO: Panic Recover

Panic

Panic์€ ๊ฒ‰์œผ๋กœ ๋ณด๊ธฐ์—๋Š” ์•„๋ฌด ๋ฌธ์ œ๊ฐ€ ์—†์ง€๋งŒ ์‹คํ–‰์„ ํ•ด๋ณด๋ฉด ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•ด์„œ ํ”„๋กœ๊ทธ๋žจ์„ ์ข…๋ฃŒํ•˜๋Š” ๊ธฐ๋Šฅ์„ ๋งํ•œ๋‹ค.

func main() {
    panic("Error in main")
}

์ด๋Ÿฐ์‹์œผ๋กœ ๊ฐ•์ œ๋กœ panic์„ ๋ฐœ์ƒ ์‹œํ‚ฌ ์ˆ˜ ์žˆ๋‹ค.

์˜ค๋ฅ˜์™€ ์—๋Ÿฌ์˜ ์ฐจ์ด

์˜ค๋ฅ˜: ํ”„๋กœ๊ทธ๋žจ์ƒ ํ—ˆ์šฉํ•˜์ง€ ์•Š๋Š” ๋ฌธ๋ฒ•๊ณผ ๊ฐ™์€ ๋น„์ •์ƒ์ ์ธ ์ƒํ™ฉ

func main(){
    var num int = 10.5 //์˜ค๋ฅ˜
}

์—๋Ÿฌ: ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰๋˜๋ฉด์„œ ๋…ผ๋ฆฌ์ƒ์œผ๋กœ ๋ถ€์ ํ•ฉํ•œ ์ƒํ™ฉ์ด ๋ฐœ์ƒํ•˜๋Š” ๊ฒƒ

func main(){
    var num1, num2 int = 10, 0
    fmt.Println(num1 / num2) //์—๋Ÿฌ
}

Recover

Recover์€ panic์„ ๋ง‰๋Š” ํ•จ์ˆ˜๋ฅผ ์˜๋ฏธํ•œ๋‹ค.
panic ์ƒํ™ฉ์ด ๋ฐœ์ƒ ํ–ˆ์„๋•Œ ํ”„๋กœ๊ทธ๋žจ์„ ์ข…๋ฃŒํ•˜์ง€ ์•Š๊ณ  ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ค€๋‹ค. defer ๊ตฌ๋ฌธ๊ณผ ํ•ญ์ƒ ๊ฐ™์ด ์‚ฌ์šฉ์„ ํ•ด์•ผํ•จ

package main

import "fmt"

func panicTest() {
	defer func() {
		r := recover() //๋ณต๊ตฌ ๋ฐ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ ์ดˆ๊ธฐํ™”
		fmt.Println(r) //์—๋Ÿฌ ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ
	}()

	var num1, num2 int
	fmt.Scanln(&num1, &num2)
	result := num1 / num2
	fmt.Println(result)
}

func main() {
	for {
		panicTest()
		fmt.Println("Hello, world!") // panic์ด ๋ฐœ์ƒํ–ˆ์ง€๋งŒ ๊ณ„์† ์‹คํ–‰๋จ
	}
}
10๊ณผ 0์„ ์ž…๋ ฅ์‹œ
10 0
runtime error: integer divide by zero
Hello, world!

10๊ณผ 1์„ ์ž…๋ ฅ์‹œ
10 1
10
<nil>
Hello, world!
  1. ํ”„๋กœ๊ทธ๋žจ์ด ์ข…๋ฃŒ๋˜๊ธฐ ์ „์— ์‹คํ–‰ ๋˜์–ด์•ผ ํ•จ์œผ๋กœ defer๊ฐ€ ์„ ์–ธ๋œ ํ•จ์ˆ˜ ์•ˆ์—์„œ ์“ฐ์ž„
  2. ์—๋Ÿฌ ๋ฉ”์„ธ์ง€๋ฅผ ๋ฐ˜ํ™˜ํ•จ. ๋”ฐ๋ผ์„œ ๋ณ€์ˆ˜์— ์ดˆ๊ธฐํ™”ํ•ด์„œ ์—๋Ÿฌ๋ฉ”์„ธ์ง€๋ฅผ ์ถœ๋ ฅ ํ•  ์ˆ˜ ์žˆ์Œ. ๋ณ€์ˆ˜์— ์ดˆ๊ธฐํ™” ํ•˜์ง€ ์•Š์œผ๋ฉด ๋”ฐ๋กœ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ์ถœ๋ ฅํ•˜์ง€ ์•Š์Œ

Categories:

Updated:

Leave a comment