java try catch 练习 数组越界

java try catch 练习 数组越界

import java.util.Scanner;

public class Main {
    
    public static void getArrN(){
        int[] a = new int[10];
        Scanner scanner = new Scanner(System.in);
        int i = scanner.nextInt();

        a[i] = 10;
    System.out.println("hello");
    }
    
    
  public static void k(){
        try {
            getArrN();
            System.out.println("try in K(), run h()");
        }catch(NullPointerException e){
      System.out.println("k()");
      throw e;
        }finally{
      System.out.println("Finally, we have executed this program ");
        }
  }

    public static void main(String[] args){
        try{
            k();
        }catch (ArrayIndexOutOfBoundsException e){
      System.out.println("Caught Erroe");
      System.out.println(e.getMessage());
      System.out.println(e);
      e.printStackTrace();
        }
    }
}

运行结果

9
hello
try in K(), run h()
Finally, we have executed this program 


10
Finally, we have executed this program 
Caught Erroe
10
java.lang.ArrayIndexOutOfBoundsException: 10
posted @ 2021-07-11 00:21  SKPrimin  阅读(144)  评论(0编辑  收藏  举报