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

Java 为什么我需要在main方法中抛出NullPointerException?,java,Java,为什么我需要在main方法中抛出NullPointerException?在“抓”区发生了什么?如果有人能详细解释的话,那将是一个很大的帮助。提前谢谢 public class GFG { public static void main(String[]args) throws NullPointerException { Scanner sc= new Scanner(System.in); System.out.println("Enter the array size"

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

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()+" ");

    }
}
}
公共类GFG{
公共静态void main(字符串[]args)引发NullPointerException{
扫描仪sc=新的扫描仪(System.in);
System.out.println(“输入数组大小”);
int n=sc.nextInt();
int[]arr=新的int[n];

对于(int i=0;i您不需要抛出
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-and-catch,但拥有它们仍然是安全的。如果你仍然想扔掉它,以下是方法:

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

“需要”抛出它吗?你不需要。
NullPointerException
是一个
RuntimeException
,你不需要声明这些异常。(它还表示存在编程错误。)我建议你花几天时间研究异常——它们是什么,如何发生,如何诊断它们,如何处理它们。