Recover 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{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 recover the panic and print the message: "catched!" if the panic occurs.

Sample Input 1:

3

Sample Output 1:

catched!
Write a program in Go
package main

import "fmt"

func main() {
? func() {
if ?() != ? {
fmt.Println("catched!")
}
}()
var numbers = []int{1, 2, 3}
var index int

fmt.Scan(&index)

fmt.Println(numbers[index])
}
___

Create a free account to access the full topic