DEV Community

Cover image for recover from panic in Golang
Amit Tiwary
Amit Tiwary

Posted on • Edited on

recover from panic in Golang

I am back after almost a year. Next few blogs will be on golang. Go is good language to build efficient and reliable software. Like any other programming language, there is possibility of error also in Go. Compile time errors detected by compiler before application run. Runtime time error occur during program execution, and if it is not handle properly, it can break the application and abort program. While writing code, a programmer try to cover all the error scenario, but there is possibility we might not handle some errors. When runtime error occur, it refer as program panicked. Runtime error is panic in golang.

Recover is a built-in function provided by go to handle panic. A recover can stop a panic from aborting the program. A recover function can handle the panic in the goroutine that has implemented the recover and not all goroutine. You can refer the below code to understand how recover handle the panic in respective goroutine.

package gortntry

import "fmt"

func panicFun(flag int) {
    if flag == 2 {
        defer func() {
            recover()
        }()
    }
    fmt.Println("inside the panic func")
    panic("panic in goroutine")
}

func TryPanic(flag int) {
    if flag == 1 || flag == 2 {
        defer func() {
            recover()
        }()
    }
    go panicFun(flag)
    panic("panic in main")
}
Enter fullscreen mode Exit fullscreen mode

We have two function TryPanic and panicFunc. TryPanic is the main entry function, and we call panicFunc inside it. Recover enabled in TryPanic for flag value 1 or 2 and in panincFunc for value 2. I have used defer here that I will explain in different blog post.

When we pass flag value 1 in TryPanic the output is:

panic: panic in goroutine

goroutine 5 [running]:
golibcustom/goroutineplgrnd.panicFun(0x0?)
    /Users/amitt/Documents/Personal Data/personalproj/go-practice/goroutineplgrnd/gortn-panic.go:13 +0x50
created by golibcustom/goroutineplgrnd.TryPanic in goroutine 1
    /Users/amitt/Documents/Personal Data/personalproj/go-practice/goroutineplgrnd/gortn-panic.go:22 +0x64
exit status 2
Enter fullscreen mode Exit fullscreen mode

It means recover in TryPanic handle the main goroutine panic but not the panic that occur in other goroutine in panicFunc.

For flag value 2 there is no panic because both goroutine has recover function.

If we use any other value for example 3 then main goroutine panic and it abort the program without waiting for the panicFunc.

panic: panic in main

goroutine 1 [running]:
golibcustom/goroutineplgrnd.TryPanic(0x2)
    /Users/amitt/Documents/Personal Data/personalproj/go-practice/goroutineplgrnd/gortn-panic.go:23 +0x78
main.main()
    /Users/amitt/Documents/Personal Data/personalproj/go-practice/main.go:36 +0x20
exit status 2
Enter fullscreen mode Exit fullscreen mode

Top comments (0)