Go 주요 주제
Go defer, panic and recover
Run cleanup code when a function returns, and turn a panic back into an ordinary error.
배울 내용
- defer
- Deferred calls run in reverse
- recover
readConfig()
- 1
open fileruns first - 2
defer closescheduled - 3
read settingsruns second - 4
close fileruns on return
Cleanup that always runs
defer schedules a call to run when the surrounding function returns, which makes it the usual way to close files and release locks. A panic stops the normal flow, and recover, called in a deferred function, catches it.
close file prints after read settings because the deferred call runs when readConfig returns. Dividing by zero panics; the deferred function recovers and stores an error in the named result err. The three deferred calls in main run last, in reverse order.
핵심 포인트
- A deferred call runs when the function returns.
- Several defers run last in, first out.
- recover catches a panic inside a deferred function.
실행 가능한 Go 예제
Go
main.go
package main
import "fmt"
func readConfig() {
fmt.Println("open file")
defer fmt.Println("close file") // runs when the function returns
fmt.Println("read settings")
}
func safeDivide(a, b int) (result int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered: %v", r)
}
}()
return a / b, nil
}
func main() {
readConfig()
for i := 1; i <= 3; i++ {
defer fmt.Println("deferred", i) // last in, first out
}
fmt.Println(safeDivide(10, 2))
fmt.Println(safeDivide(1, 0))
}
open file
read settings
close file
5 <nil>
0 recovered: runtime error: integer divide by zero
deferred 3
deferred 2
deferred 1연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
모든 챌린지