繁体   English   中英

为什么我需要在 main 方法中抛出 NullPointerException?

[英]Why do I need to throw NullPointerException in the main method?

为什么我需要在 main 方法中抛出 NullPointerException? “catch”块中发生了什么? 如果有人能详细解释一下,那将是一个很大的帮助。 提前致谢

public class GFG {

public static void main(String[]args) throws NullPointerException {

    Scanner sc= new Scanner(System.in);
    System.out.println("Enter the array size");
    int n= sc.nextInt();
    int [] arr= new int[n];
    for (int i = 0; i <arr.length ; i++) {
        arr[i]=sc.nextInt();
    }
    printRepeating(arr);
}

static void printRepeating(int[]arr){

     Map<Integer,Integer> map= new LinkedHashMap<Integer,Integer>();
    for(int i=0;i<arr.length;i++)
    {
        try {
            map.put(arr[i], map.get(arr[i]) + 1);
        }
        catch (Exception e) {
            map.put(arr[i], 1);
        }


    }
    for (Entry<Integer, Integer> e:map.entrySet()) {
        if(e.getValue()>1)

            System.out.print(e.getKey()+" ");

    }
}
}

您不需要抛出NullPointerException 此异常从RuntimeException扩展而来,因此它是一个未经检查的异常。 在编译期间不会检查这些异常(编译器不必指定或捕获它们)。 这些都与代码本身的错误有关; 我建议阅读有关未经检查的异常的信息。 只有高级程序才会抛出这些异常,所以我建议将代码更改为:

try {
    if (map.containsKey(arr[i]){
        map.put(arr[i], map.get(arr[i]) + 1);
    }else{
        map.put(arr[i], 1);
}catch (Exception e) {
    e.printStackTrace();
}

我会删除尝试和捕捉,但拥有它们仍然是安全的。 如果你仍然想扔它,这里是如何:

try {
    map.put(arr[i], map.get(arr[i]) + 1);
}catch (NullPointerException e) {
    map.put(arr[i], 1);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM