关于java异常处理

为啥后面的catch没反应?

img


package test9;

import java.util.;
public class WpjException4 {
public static double multi(int n)
{if(n<0) throw new IllegalArgumentException("输入了负数异常");
double s=1;
for(int i=1;i<=n;i++) s=s
i; return s ; }
public static void main(String[] args) {

Scanner bb=new Scanner(System.in);
try
{ int n=bb.nextInt();
System.out.println(n+"!="+multi(n));}
catch (ArrayIndexOutOfBoundsException e){ System.out.println("应该输入一个整数");}
catch (NumberFormatException e1)
{ System.out.println("应该输入一个数");}
catch (IllegalArgumentException e2)
{ System.out.println("出现的异常为:"+e2.toString());}
finally
{ System.out.println("计算阶乘结束");}
}

}

catch只会捕获你写的其中一种异常啊。其他当然不会捕获。相当于if 语句一样了
如果你的catch 都没有触发,说明报错不在你catch范围内
你可以把catch中替换成 Exception 这样就可以捕获到

异常错误了呀,这个是数组越界的 ,输入数字异常的是 InputMismatchException 或者最外层直接抛出Exception

img