Golang defer๊ณผ panic - Go series(12)

Date:     Updated:

Categories:

Tags: ,

image

์ง€์—ฐ์‹คํ–‰์„ ํ•ด์ฃผ๋Š” defer

defer ํ‚ค์›Œ๋“œ๋Š” ํŠน์ • ๋ฌธ์žฅ ๋˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋‚˜์ค‘์— ์‹คํ–‰๋˜๊ฒŒ ํ•œ๋‹ค.(ํ˜ธ์ถœ ๋œ ํ•จ์ˆ˜์˜ ๋งˆ์ง€๋ง‰์— ์‹คํ–‰๋œ๋‹ค) ์ผ๋ฐ˜์ ์œผ๋กœ defer๋Š” C#, java ์—์„œ์˜ finally์ฒ˜๋Ÿผ ์‚ฌ์šฉ๋œ๋‹ค.

package main

import "os"

func main(){
    read_file,err := os.Open("C:\\g\\a.txt")
    if err!=nil{
        println(err)
    }
    defer read_file.Close()

    bytes := make([]byte, 1024)
    read_file.read(bytes)
    println(bytes)
}

panic !?!?

ํ˜„์žฌ ํ•จ์ˆ˜์˜ ์‹คํ–‰์„ ์ฆ‰์‹œ ๋ฉˆ์ถ”๊ณ  ํ˜„์žฌ ํ•จ์ˆ˜ ๋ฐ”๋”” ๋‚ด์— ์กด์žฌํ•˜๋Š” defer์„ ๋ชจ๋‘ ์‹คํ–‰ํ•˜๊ณ  ์ฆ‰์‹œ ๋ฆฌํ„ดํ•˜๊ฒŒ ๋œ๋‹ค.
์ด panic์€ ํŠน์ดํ•˜๊ฒŒ ์ƒ์œ„ ํ•จ์ˆ˜๊นŒ์ง€๋„ ์ ์šฉ์ด ๋˜๊ณ  ๋งˆ์ง€๋ง‰์— ํ”„๋กœ๊ทธ๋žจ์ด ์—๋Ÿฌ๋ฅผ ๋‚ด๊ณ  ์ข…๋ฃŒํ•˜๊ฒŒ ๋œ๋‹ค.

package main

import "os"

func main() {
    // ์ž˜๋ชป๋œ ํŒŒ์ผ๋ช…์„ ๋„ฃ์Œ
    openFile("Invalid.txt")

    // openFile() ์•ˆ์—์„œ panic์ด ์‹คํ–‰๋˜๋ฉด
    // ์•„๋ž˜ println ๋ฌธ์žฅ์€ ์‹คํ–‰ ์•ˆ๋จ
    println("Done")
}

func openFile(fn string) {
    f, err := os.Open(fn)
    if err != nil {
        panic(err)
    }

    defer f.Close()
}

recover! -> ํŒจ๋‹‰์„ ๋ฐ˜๋Œ€๋กœ

recover์ด defer ์•ˆ์— ์žˆ์„ ์‹œ์—๋Š” ํ˜„ ํ•จ์ˆ˜๊ฐ€ ๋๋‚œ ๋’ค ์ƒ์œ„ ํ•จ์ˆ˜์—์„œ๋Š” defer๋งŒ ์‹คํ–‰๋˜์ง€ ์•Š๊ณ  ์ผ๋ฐ˜์ ์œผ๋กœ ์ง„ํ–‰์ด ๋œ๋‹ค.

package main

import (
    "fmt"
    "os"
)

func main() {
    // ์ž˜๋ชป๋œ ํŒŒ์ผ๋ช…์„ ๋„ฃ์Œ
    openFile("Invalid.txt")

    // recover์— ์˜ํ•ด
    // ์ด ๋ฌธ์žฅ ์‹คํ–‰๋จ
    println("Done")
}

func openFile(fn string) {
    // defer ํ•จ์ˆ˜. panic ํ˜ธ์ถœ์‹œ ์‹คํ–‰๋จ
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("OPEN ERROR", r)
        }
    }()

    f, err := os.Open(fn)
    if err != nil {
        panic(err)
    }

    defer f.Close()
}

Leave a comment