实验报告六一【实验目的】1.掌握异常的基本概念。
2.理解异常处理机制。
3.掌握创建自定义异常的方法。
二【实验内容】Java提供了异常处理机制,当程序中发生异常时,程序产生一个异常事件,相应地生成异常对象。
系统从生成对象的代码开始,沿方法的调用栈逐层回溯,寻找相应的处理代码,并把异常对象交给该方法处理。
实验1 录入如下源程序:1、public class Ex7_1 {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...");}}2、保存程序Ex7_1.java,编译运行程序,观察并分析程序的运行结果。
The quick brown fox jumpsover the lazy dog.Exception in thread "main" ng .ArrayIndexOutOfBoundsException atEx7_1.main(Ex7_1.java:9),可以看出,在第9行出现了数组下标越界的异常,导致了程序的中止,而程序的最后一条语句“System.out.println("haha...");”没有执行。
运行结果:3、我们修改程序,加入异常处理,当程序发生异常时,经过异常处理后,程序还可以继续执行。
异常处理代码格式:try{//可能有问题的代码}catch(ArrayIndexOutOfBoundsException e){//处理代码break;}catch(Exception e1){///}catch(…..){ }修改代码在可能出错的地方加入:try{//}catch(ArrayIndexOutOfBoundsException e){System.out.println();System.out.println("下标越界异常处理!");System.out.println(e.toString());break;}代码:运行结果:4、重新编译运行程序,对比运行结果。
在catch后加入:finally{System.out.println("不管怎样都要执行的语句!");}再重新编译运行,对比运行结果。
代码:运行结果:5、除了下标越界的异常外,还有几个常用的异常,如:ArithmeticException、NullPointerException、NegativeArraySizeException、ArrayIndexOutOfBoundsException等。
试编写一个除数为0的异常处理过程。
代码:public class EX6_1 {public static void main(String[] args) {int a,b,c;try{a = 2;b = 0;c = a / b;System.out.println("c = "+c);}catch(ArithmeticException e){System.out.println("算术运算异常");System.out.println("除数b不能为0");}finally{System.out.println();System.out.println("程序结束!");}}}运行结果: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) t hrow new MyException(“结果re=”+re+“超过了”+1000);return re;}完善这个程序,并测试。
代码:public class MyException extends Exception{public MyException(String str){super(str);}}public class TextException6_1 {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;}public static void main(String[] args) {TextException6_1 te = new TextException6_1();try{System.out.println(Multiply(100,100));}catch(MyException e){System.out.println(e.getMessage());}try{System.out.println(Multiply(10,10));}catch(MyException e){System.out.println(e.getMessage());}}}运行结果:实验21、编写一个计算器,它从键盘中读取操作数和操作符,经过计算后,在屏幕上输出结果。
如下源程序:import java.io.*;public class Calculator {public static void main(String[] args) {Calculator cal=new Calculator();cal.Calculate();}public double ReadDouble() {// 从键盘读取一个Double数double re=0;DataInputStream in =new DataInputStream(System.in);try{String temp =in.readLine();re =Double.parseDouble(temp);}catch (IOException e) {System.out.println("Error in I/O:" + e.getMessage());}return re;}public void Calculate() {// 计算byte cmd='q';do{double op1,op2,re=0;byte op;System.out.print("请输入操作数1:");op1 =ReadDouble();System.out.print("请输入操作(+、-、*、/):");op =ReadByte();System.out.print("请输入操作数2:");op2 =ReadDouble();switch(op){case '+':re =op1 +op2;break;case '-':re =op1 -op2;break;case '*':re =op1 *op2;break;case '/':re =op1 /op2;break;default:System.out.println("操作符错误");continue;}System.out.println(""+op1+(char)op+op2+"="+re);System.out.print("退出?(Q/q)");cmd =ReadByte();}while(cmd!='Q' && cmd!='q');}public byte ReadByte() {// 读操作符byte cmd[] =new byte[10];try{System.in.read(cmd);}catch (IOException e) {System.out.println("Error in I/O:" + e.getMessage());}return cmd[0];}}2、保存程序Calculator.java,编译程序,运行并测试程序。
运行结果:3、试编写一个程序完成文件拷贝功能,即从文件A中读取数据,再写到文件A的拷贝——文件B中。
注意异常的处理(用字节流处理)先在D盘创建两个txt文件A.txt和B.txt,在A.txt中保存数据I am a student!代码:import java.io.*;public class FileIOStream {public static void main(String[] args) throws IOException{ try{FileInputStream in = new FileInputStream("D:\\A.txt");FileOutputStream out = new FileOutputStream("D:\\B.txt");int i;while((i=in.read()) != -1){out.write(i);}out.close();in.close();System.out.println("完成数据拷贝!");}catch(FileNotFoundException e){e.printStackTrace();}}}运行结果:将以上各题的源程序、运行结果写在该题后面,以及实验中遇到的问题和解决问题的方法,以及实验过程中的心得体会,写在下面的空白中。