Inspectopedia
 
2024.3

Defer/go statement calls 'recover' or 'panic' directly

Info
Reliability
New
Last modified: 03 December 2024

Reports defer and go statements that call panic() or recover() directly.

Such statements are rarely useful and might indicate a misuse of the panic() and recover() mechanism. In particular:

  • go panic(): a newly-started goroutine will panic immediately.

  • defer panic(): a function with this statement will always panic on exit.

  • go recover(): has no effect as newly-started goroutine cannot panic.

  • defer recover(): function with this statement will silently stop panicking. This could be a valid usage, but an idiomatic way is to inspect the value returned by recover():

    defer func() {
      if r := recover(); r != nil {
        fmt.Println("Recovered from: ", r)
      }
    }()

For more information about go statements and panics handling, refer to Handling panics and Go statements in the Go Language Specification.