java实例_出错处理 [超过1000&除数为零]
Java 提供了异常处理机制,当程序中发生异常时,程序产生一个异常事件,相应地生成异常对象。系统从生成对象的代码开始,沿方法的调用栈逐层回溯,寻找相应的处理代码,并把异常对象交给该方法处理。1.新建一个 project,在 main 里面输入以下程序:String output[] = {"The ","quick ","brown ","fox ","jumps ","over ","the ","lazy","dog."};int i= 0;while(i<12){System.out.print(output[i++]);}System.out.println("haha...");2.保存程序 编译运行程序,观察并分析程序的运行结果。可以看出,在第 9 行出现了数组下标越界的异常,导致了程序的中止,而程序的最后一条语句“System.out.println("haha...");”没有执行。3.修改程序,加入异常处理,当程序发生异常时,经过异常处理后,程序还可以继续执行。修改代码如下:String output[] ={ "The ","quick ","brown ","fox ","jumps ", "over ","the ","lazy ","dog."};int i =0;while(i<12){try{System.out.print(output[i++]);}catch(ArrayIndexOutOfBoundsException e) {System.out.println();System.out.println("下标越界异常处理!");System.out.println(e.toString());break;}}System.out.println("haha..."); }4. 重新编译运行程序,对比运行结果。在 catch 语句后加入:finally{ System.out.println("不管怎样都要执行的语句!"); }再重新编译运行,对比运行结果。5. 【要上交实验】除了下标越界的异常外,还有几个常用的异常,如:ArithmeticException、NullPointerException、NegativeArraySizeException、ArrayIndexOutOfBoundsException 等。试编写一个除数为 0 的异常处理过程。6.除了使用系统定义的异常外,用户还可以自定义异常。其格式为:public class MyException extends Exception{…}试自定义一个异常,在计算两个数乘积的方法(Multiply)中,如果结果超过 1000 则抛出这个异常。方法 Multiply 定义如下:Static int Multiply(int n,int m) throws MyException{int re;re =n*m;if(re>1000) throw new MyException(“结果 re=”+re+“超过了”+1000);return re;}
代码实现
package Lab8;
public class Lab8 {
public static double getArith(double a, double b)throws ArithmeticException {
ArithmeticException ex = new ArithmeticException("对不起,除数为0");
if (b == 0) {
throw ex;
}
return a / b;
}
public int Multiply(int n,int m) throws ArithmeticException{
int re;
re =n*m;
ArithmeticException ex = new ArithmeticException("结果 re="+re+"超过了"+1000);
if(re>1000) throw ex;
return re;
}
public static void main(String[] args) {
/*错误代码 数组下标越界*/
// String output[] = {"The ","quick ","brown ","fox ","jumps ","over ","the ","lazy","dog."};
// int i= 0;
// while(i<12){
// System.out.print(output[i++]);
// }
// System.out.println("haha...");
// }
String output[] ={"The ","quick ","brown ","fox ","jumps ", "over ","the ","lazy ","dog."};
int i =0;
while(i<12){
try{
System.out.print(output[i++]);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println();
System.out.println("下标越界异常处理!");
System.out.println(e.toString());
break;
}
finally{ System.out.println("不管怎样都要执行的语句!"); }
}
System.out.println("haha...");
/*ArithmeticException处理除数为零*/
try {
System.out.println(getArith(Double.parseDouble("1"), Double
.parseDouble("0")));
} catch (Exception e) {
e.printStackTrace();
}
/*ArithmeticException100*100超过1000*/
try {
Lab8 t=new Lab8();
System.out.println(t.Multiply(100,100));
} catch (Exception e) {
e.printStackTrace();
}
}
}