80

With the following code, if no file argument is given, a panic is thrown for line 9 panic: runtime error: index out of range as expected.

How can I 'catch' this panic and handle it when directly when passing something to it (os.Args[1]) that causes the panic? Much like try/catch in PHP or try/except in Python.

I've had a search here on StackOverflow but I've not found anything that answers this as such.

package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Open(os.Args[1])
    if err != nil {
        fmt.Println("Could not open file")
    }
    fmt.Printf("%s", file)
}

8 Answers 8

156

A panicking program can recover with the builtin recover() function:

The recover function allows a program to manage behavior of a panicking goroutine. Suppose a function G defers a function D that calls recover and a panic occurs in a function on the same goroutine in which G is executing. When the running of deferred functions reaches D, the return value of D's call to recover will be the value passed to the call of panic. If D returns normally, without starting a new panic, the panicking sequence stops. In that case, the state of functions called between G and the call to panic is discarded, and normal execution resumes. Any functions deferred by G before D are then run and G's execution terminates by returning to its caller.

The return value of recover is nil when the goroutine is not panicking or recover was not called directly by a deferred function. Conversely, if a goroutine is panicking and recover was called directly by a deferred function, the return value of recover is guaranteed not to be nil. To ensure this, calling panic with a nil interface value (or an untyped nil) causes a run-time panic.

Here is an example of how to use this:

// access buf[i] and return an error if that fails.
func PanicExample(buf []int, i int) (x int, err error) {
    defer func() {
        // recover from panic if one occurred. Set err to nil otherwise.
        if (recover() != nil) {
            err = errors.New("array index out of bounds")
        }
    }()

    x = buf[i]
}

Notice that more often than not, panicking is not the right solution. The Go paradigm is to check for errors explicitly. A program should only panic if the circumstances under which it panics do not happen during ordinary program executing. For instance, not being able to open a file is something that can happen and should not cause a panic while running out of memory is worth a panic. Nevertheless, this mechanism exists to be able to catch even these cases and perhaps shut down gracefully.

14
  • 68
    Please comment before downvoting. Why are you downvoting me for giving an answer for the literal question OP asked? OP specifically stated that he wants to recover from a panic. I wrote an answer how to do that. Whether it's the right thing to do is not mine to judge.
    – fuz
    Jul 29, 2014 at 21:51
  • 22
    @Volker If he'd ask that, I would give him an honest answer. I might point out in an additional comment that this might not be the smartest thing to do. Who am I to judge the questions of others?
    – fuz
    Jul 29, 2014 at 21:59
  • 43
    For future reference (since no one has mentioned it): inhaling jelly beans and/or mustard is a bad idea. Consider a different approach to whatever problem you are having. Jul 29, 2014 at 22:25
  • 3
    Panic only when you know you can't continue, only crash. Crashing may mean quitting the whole program, returning an "internal error" message from an API or Web request, or ending some other high-level chunk of your program. Panics are slow, un-idiomatic, and easy to mess up use of (particularly when you have 80% err returns and 20% panics; you get the downsides of both), so don't use them for potentially recoverable situations like missing/duplicate object in database, network error, etc. Also, if writing a library, return err whenever the caller might be able to recover.
    – twotwotwo
    Jul 30, 2014 at 4:49
  • 3
    Came to this question to find out how to handle panics in go. This should be the accepted answer.
    – mclaassen
    Apr 3, 2016 at 16:34
49

Go is not python, you should properly check for args before you use it:

func main() {
    if len(os.Args) != 2 {
         fmt.Printf("usage: %s [filename]\n", os.Args[0])
         os.Exit(1)
    }
    file, err := os.Open(os.Args[1])
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s", file)
}
4
  • 3
    Minor nit: you probably want either log.Fatal(err) (or possibly os.Exit after printing the message with err in it) in that final if block.
    – Dave C
    Apr 14, 2015 at 17:59
  • 9
    "Go is not python, you should properly check for args before you use it:" true but you probably want to do stuff like this within a test to check that your program is panicking as desired without throwing an error. recover seems to be the way to accomplish a typical try catch
    – dkinzer
    Jul 24, 2016 at 12:45
  • 2
    This is not a proper answer. In any language, you should check for possible errors and exceptions. The problem is that developers are human and make mistakes. The point of the question is to handle the panics when the developer has failed to handle the possible errors properly. The "too bad, you should have had thought about it" answer has never been helpful.
    – Ramtin
    Feb 1 at 7:33
  • Go and Python both terminate the program with a stack trace for the error in question. Mar 24 at 23:52
21

Some Golang official packages use panic/defer+recover as throw/catch, but only when they need to unwind a large call stack. In Golang's json package using panic/defer+recover as throw/catch is the most elegant solution.

from http://blog.golang.org/defer-panic-and-recover

For a real-world example of panic and recover, see the json package from the Go standard library. It decodes JSON-encoded data with a set of recursive functions. When malformed JSON is encountered, the parser calls panic to unwind the stack to the top-level function call, which recovers from the panic and returns an appropriate error value (see the 'error' and 'unmarshal' methods of the decodeState type in decode.go).

Search for d.error( at http://golang.org/src/encoding/json/decode.go

In your example the "idiomatic" solution is to check the parameters before using them, as other solutions have pointed.

But, if you want/need to catch anything you can do:

package main

import (
    "fmt"
    "os"
)

func main() {

    defer func() { //catch or finally
        if err := recover(); err != nil { //catch
            fmt.Fprintf(os.Stderr, "Exception: %v\n", err)
            os.Exit(1)
        }
    }()

    file, err := os.Open(os.Args[1])
    if err != nil {
        fmt.Println("Could not open file")
    }

    fmt.Printf("%s", file)
}
16

First: You wouldn't want to do this. Try-catch-style error handling is no error handling. In Go you would check len(os.Args) first and access element 1 only if present.

For the rare cases you need to catch panics (and your case is not one of them!) use defer in combination with recover. See http://golang.org/doc/effective_go.html#recover

1
8

We can manage panic without halting process using recover. By calling recover in any function using defer it will return the execution to calling function. Recover returns two values one is boolean and other one is interface to recover. Using type assertion we can get underlying error value You can also print underlying error using recover.

defer func() {
    if r := recover(); r != nil {
        var ok bool
        err, ok = r.(error)
        if !ok {
            err = fmt.Errorf("pkg: %v", r)
        }
    }
}()
5

I had to catch panics in a test case. I got redirected here.

func.go

var errUnexpectedClose = errors.New("Unexpected Close")
func closeTransaction(a bool) {
    if a == true {
        panic(errUnexpectedClose)
    }
}

func_test.go

func TestExpectedPanic() {
    got := panicValue(func() { closeTransaction(true) })
    a, ok := got.(error)
    if a != errUnexpectedClose || !ok {
        t.Error("Expected ", errUnexpectedClose.Error())
    }
}

func panicValue(fn func()) (recovered interface{}) {
    defer func() {
        recovered = recover()
    }()
    fn()
    return
}

Used from https://github.com/golang/go/commit/e4f1d9cf2e948eb0f0bb91d7c253ab61dfff3a59 (ref from VonC)

3

Note that the recover treatment of a panic Execution error (such as attempting to index an array out of bounds trigger) might change with go 1.7 after issue 14965

See CL 21214 and its test:

runtime: make execution error panic values implement the Error interface

Make execution panics implement Error as mandated by Run-time panics (specs), instead of panics with strings.

When you recover a panic error, you would be able to do:

if _, ok := recovered.(runtime.Error); !ok {

This is still being evaluated, and as Dave Cheney. mentions:

I don't know what people are currently doing but from my POV this has been broken for a long time and nobody has complained so they are either explicitly relying on the broken behaviour, or nobody cares. Either way I think it's a good idea to avoid making this change.

3
  • The linked issue has been closed due to its age, not because implemented.
    – apaderno
    Mar 17, 2021 at 7:06
  • @kiamlaluno It was first closed in 2016, because implemented by golang.org/cl/21214 and github.com/golang/go/commit/…. Then it was limited to collaborators, and finally, indeed, closed due to age. But it was implemented.
    – VonC
    Mar 17, 2021 at 8:48
  • Oh, thank you. They didn't put any explicit, not created by bots, comment on the Github issue, and it seemed they didn't do anything to fix/change that. (The link to follow is indeed the one for CL 21214.)
    – apaderno
    Mar 17, 2021 at 9:04
1

While panic in Go isn't idiomatic and shouldn't be used as exceptions in other programming languages, sometimes the need to catch them does arise.

In these cases I've found it useful to define a CatchPanic utility that translate panic into a checkable error to minimize divergence from Go's idioms.

For example:

func CatchPanic[T interface{}](f func() T) (ret T. err error) {
    defer func() {
        rec = recover()
        if rec != nil {
            err = errors.New(fmt.Sprint(rec))
        }
    }()
    return f(), nil
}

Usage example (oversimplified..):

func main() {
    arr := []int{0, 1, 2, 3, 4}
    val, err := CatchPanic(func() int {
        return arr[5] // Will panic
    })
    if err != nil {
        // Handle error
    }
}

The return value of the lambda parameter can be adjusted to other use cases.

Do note that when possible it's advised not to relay on panic catching in Go and check before access is preferable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.