Catching panics in Golang

后端 未结 7 2123
自闭症患者
自闭症患者 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条回答
  •  無奈伤痛
    2021-01-31 07:59

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

提交回复
热议问题