Answer the question
In order to leave comments, you need to log in
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)
}
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
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.
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)
}()
#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
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question