Catching panics in Golang

后端 未结 7 2094
自闭症患者
自闭症患者 2021-01-31 07:24

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\

7条回答
  •  Happy的楠姐
    2021-01-31 07:43

    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)
    }
    

提交回复
热议问题