为什么需要在main方法中抛出NullPointerException? “catch” block 中发生了什么?如果有人能详细解释一下,那将是一个很大的帮助。提前致谢
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 和 catch,但拥有它们仍然是安全的。如果您仍然想扔掉它,请按以下步骤操作:
try {
map.put(arr[i], map.get(arr[i]) + 1);
}catch (NullPointerException e) {
map.put(arr[i], 1);
}
关于java - 为什么需要在main方法中抛出NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60384082/