During first execution of the loop in the code snippet,an exception throws.my question is how to continue executing next iteration of the loop when panic happens.like try catch mechanism in java,the loop will continue executing next iteration of the loop.
package main
import (
"fmt"
)
func main() {
var arr []int = []int{5, 6, 7, 8, 9}
fmt.Println(arr)
for i := 6; i < 10; i++ {
defer func() {
fmt.Println("aaa")
if err := recover(); err != nil {
fmt.Printf("error is %v
", err)
}
}()
arr[i] = i
}
}
The issue is that your slice has a length and capacity of 5,
https://play.golang.org/p/7wy91PTPum
and you are trying to add something to the 6th position.
You need to either set a fixed size that you know will hold everything you want to put into it:
var arr [10]int = [10]int{5, 6, 7, 8, 9}
https://play.golang.org/p/GSNDXGt1Jp
Or use append
and change
arr[i] = i
to
arr = append(arr, i)
You could wrap all work inside some func, and call defer with recover inside it
package main
import (
"fmt"
)
func doSmth(arr []int, idx int) {
defer func() {
if err := recover(); err != nil {
fmt.Printf("error is %v
", err)
}
}()
arr[idx] = idx
}
func main() {
var arr []int = []int{5, 6, 7, 8, 9}
fmt.Println(arr)
for i := 6; i < 10; i++ {
doSmth(arr, i)
}
}