try{
int i;
int a[]=new int[10];
for(i=0;i<=10;i++)
{ a[i]=i;
}
}
catch(IndexOutOfBoundsException e)
{System.out.println ("异常是:"+e);}
}
static void nullPointer()
{
try{
String s;
int b;
s=null;
b=s.length();
}
catch(NullPointerException e)
{System.out.println ("异常是:"+e);}
}
}
运行结果如图1所示:
2) 编写程序实现如下功能:计算两个数之和,参与求和运算的每个数的值都必须在10-20之间,当任意一个数超出范围时,抛出自己的异常。
步骤(1):基于系统异常类Exception,定义自己的异常类NumberRangeException。 步骤(2):定义包含main方法的Application类SelfException。
步骤(3):在SelfException类中添加公共方法:
Public static int selfExceptionTest(int int1,int int2) throws NumberRangeException使之能在求int1,int2两个数和之前检查两个数的数值范围,若符合条件则求和,否则抛出异常NumberRangeException。
步骤(4):在main方法中调用selfExceptionTest方法。
步骤(5):保存文件为SelfException.java,然后编译并调试程序。
步骤(6):修改main方法中调用selfExceptionTest方法的实参,看看程序的运行结果有什么不同。