4
4
4utka_pyan2017-06-21 08:08:13
go
4utka_pyan, 2017-06-21 08:08:13

Panic catching in golang?

Let's take a working script, there is an error in it, in the loop <= instead of just <

package main
import "fmt"

func main() {
    var x [5]float64
    x[0] = 98
    x[1] = 93
    x[2] = 77

    var total float64 = 0
    for i := 0; i <= 5; i++ {
        total += x[i]
    }
    fmt.Println(total / 3)
}

Mistake:
panic: runtime error: index out of range
goroutine 1 [running]:
panic (0x4ef600, 0xc082002030)
C:/Go/src/runtime/panic.go:464 +0x3f4
main.main()
C:/Go/test/test .go: 12 +0x199
exit status 2

In general, the text panic is indicated in the first line here. Add recover
We can handle panics with the built-in recover function.
The recover function stops the panic and returns the value that was passed to the panic function.

It became:
package main
import "fmt"

func main() {
    var x [5]float64
    x[0] = 98
    x[1] = 93
    x[2] = 77

    var total float64 = 0
    for i := 0; i <= 5; i++ {
        total += x[i]
    }
    fmt.Println(total / 5)
}

defer func() {    
    str := recover()
    fmt.Println(str)
}()

But in response
#command-line-arguments
.\test.go:18: syntax error: non-declaration statement outside function body
.\test.go:19: syntax error: unexpected str, expecting (
.\test.go:19: method has no receiver
.\test.go:20: syntax error: non-declaration statement outside function body

Those. all errors are associated with the added block, and the original error is not displayed. Am I doing something wrong and how to use this function correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rustler2000, 2017-06-21
@4utka_pyan

defer must be inside main

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question