Prevent a panic

Report a typo

The code below can produce a panic if you try to scan the out-of-bounds index:

package main

import "fmt"

func main() {
    var numbers []int = []int{1, 2, 3}
    var index int

    fmt.Scan(&index)

    fmt.Println(numbers[index])
}

// Input:
// 3
// Output:
// panic: runtime error: index out of range [3] with length 3

Two conditions provide an out-of-bounds panic:

  • it must be an iterable variable;
  • an index or the bounds must be set implicitly.

You need to prevent the panic and print the message: "prevented!" if you catch incorrect data.

Sample Input 1:

-1

Sample Output 1:

prevented!
Write a program in Go
package main

import "fmt"

func main() {
var numbers = []int{1, 2, 3}
var index int

fmt.Scan(&index)

if index >= ? || ? {
fmt.Println("prevented!")
} else {
fmt.Println(numbers[index])
}
}
___

Create a free account to access the full topic