Catching panics in Golang

后端 未结 7 2008
自闭症患者
自闭症患者 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:48

    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.

提交回复
热议问题