201521123027 <java程序设计>第九周学习总结

1.本周学习总结

1.1 以你喜欢的方式(思维导图或其他)归纳总结异常相关内容。

2.书面作业

Q1.常用异常
题目5-1
1.1 截图你的提交结果(出现学号)

1.2 自己以前编写的代码中经常出现什么异常、需要捕获吗(为什么)?应如何避免?

答:我以前的代码中经常出现访问空指针(NullPointerException)和数组越界(ArrayIndexOutOfBoundsException)
(1)访问空指针(NullPointerException)
该异常由系统检测,属于Unchecked Exception,故无需使用try catch进行异常捕获。所以我们在写代码时需要用到if语句判断是否为空,来避免出现NullPointerException;
(2)数组越界(ArrayIndexOutOfBoundsException)
该异常由系统检测,属于Unchecked Exception,故无需使用try catch进行异常捕获。我们应尽量改进代码,不让数组下标越界,避免出现ArrayIndexOutOfBoundsException。

1.3 什么样的异常要求用户一定要使用捕获处理?

答:除了Error与RuntimeException及其子类以外的异常都是Check Exception,需要在代码中使用try catch进行捕获处理。

Q2.处理异常使你的程序更加健壮
题目5-2
2.1 截图你的提交结果(出现学号)

2.2 实验总结

答:此题是非整型字符串的捕获。当输入数组中的值不是整型时,需要捕获异常,而且需要将其删除,所以需要注意的是捕获异常后需要对数组下标进行i--操作。具体代码如下:
catch(NumberFormatException e){
	       System.out.println(e);
	        i--;
	    }

Q3.throw与throws
题目5-3
3.1 截图你的提交结果(出现学号)

3.2 阅读Integer.parsetInt源代码,结合3.1说说抛出异常时需要传递给调用者一些什么信息?

Integer.parsetInt源代码:
 public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }

 public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        /*
         * WARNING: This method may be invoked early during VM initialization
         * before IntegerCache is initialized. Care must be taken to not use
         * the valueOf method.
         */

        if (s == null) {
            throw new NumberFormatException("null");
        }

        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }

        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " greater than Character.MAX_RADIX");
        }

        int result = 0;
        boolean negative = false;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                if (len == 1) // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                digit = Character.digit(s.charAt(i++),radix);
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        return negative ? result : -result;
    }
答:查看源代码,发现要先使用throws抛出异常,然后if语句中使用throw抛出具体的异常原因。结合题目5-3,要求begin<end,begin不得小于0,end不得大于arr.length,否则抛出相应的异常(IllegalArgumentException`)。所以在函数名后面要使用throws,代码为public static double findMax(double[] arr,int begin, int end)throws IllegalArgumentException; 然后再具体分析不同情况if(begin>=end),if(begin<0),if(end>arr.length)抛出具体的异常原因。这样显示不同异常及其出现异常的不同情况时的原因,可以让用户立即知道出现错误的原因,做出及时的修改。

Q4.函数题
题目4-1(多种异常的捕获)
3.1 截图你的提交结果(出现学号)

3.2 一个try块中如果可能抛出多种异常,捕获时需要注意些什么?

答:当抛出多种异常时,在写catch时要注意将子类异常写在父类异常前面。若父类异常在前面。则不执行子类异常的捕获,编译会出现错误。例如:
  catch(NumberFormatException e1){
	 System.out.println(e1);//执行,若捕获到,则输出NumberFormatException;
  }
  catch(IllegalArgumentException e2){
	 System.out.println(e2);//执行,若捕获到,则输出IllegalArgumentException;
  }
  catch(Exception e3){
	 System.out.println(e3);//执行,若捕获到,则输出Exception;
  }

当改变三种异常的顺序时:
 catch(Exception e3){
	 System.out.println(e3);//执行,若捕获到,则输出Exception;
  }
 catch(NumberFormatException e1){
	 System.out.println(e1);//不执行;
  }
  catch(IllegalArgumentException e2){
	 System.out.println(e2);//不执行;
  }
 出现编译错误。

Q5.为如下代码加上异常处理

byte[] content = null;
FileInputStream fis = new FileInputStream("testfis.txt");
int bytesAvailabe = fis.available();//获得该文件可用的字节数
if(bytesAvailabe>0){
    content = new byte[bytesAvailabe];//创建可容纳文件大小的数组
    fis.read(content);//将文件内容读入数组
}
System.out.println(Arrays.toString(content));//打印数组内容

5.1 改正代码,让其可正常运行。注1:里面有多个方法均可能抛出异常。注2:要使用finally关闭资源。

修改后代码:
public static void main(String[] args, Object fis) throws IOException {
        byte[] content = null;
		FileInputStream fis=null;
		try{
		fis = new FileInputStream("testfis.txt");
		int bytesAvailabe = fis.available();//获得该文件可用的字节数
		if(bytesAvailabe>0){
		    content = new byte[bytesAvailabe];//创建可容纳文件大小的数组
		    fis.read(content);//将文件内容读入数组
		}
		}catch(Exception e){
			System.out.println(e);
		}
		finally
        {
            if(fis!=null)
                try{
                    fis.close();
                }
            catch(Exception e){
            	System.out.println(e);
            	}
        }
		System.out.println(Arrays.toString(content));//打印数组内容
	}

结果截图:

5.2 使用Java7中的try-with-resources来改写上述代码实现自动关闭资源.常用异常

public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		byte[] content = null;
		try(FileInputStream fis = new FileInputStream("testfis.txt")){
		int bytesAvailabe = fis.available();//获得该文件可用的字节数
		if(bytesAvailabe>0){
		    content = new byte[bytesAvailabe];//创建可容纳文件大小的数组
		    fis.read(content);//将文件内容读入数组
		}
		}catch(Exception e){
			System.out.println(e);
		}
		System.out.println(Arrays.toString(content));//打印数组内容
	}

结果截图:

Q6.重点考核:使用异常改进你的购物车系统(未提交,得分不超过6分)
举至少两个例子说明你是如何使用异常处理机制让你的程序变得更健壮。
说明要包含2个部分:1. 问题说明(哪里会碰到异常)。2.解决方案(关键代码)

1.问题说明

(1)当购买一件商品后,开始进行选择"是否继续购买,1.继续,0.退出"时,若出现输入的是其他字符就会出现异常;
(2)当输入购买的商品数量时,若输入的是其他字符,不是整型数时会出现异常。

2.关键代码

(1)
System.out.println("是否继续购买,1.继续,0.退出");
			try{
				r=in.nextInt();
			}catch(InputMismatchException e){
				System.out.println(e);
			}
(2)
System.out.print("请输入购买的数量:");
			try{for(int j=0;j<10;j++){
				if(a[j].getName().equals(str)){
					Goods b=new Goods(a[j].getName(),a[j].getId(),a[j].getPrice(),in.nextInt());
					com.add(b);
					break;
				}
				}
			}catch(NumberFormatException e1){
				System.out.println(e1);
			}

3.码云上代码提交记录

3.1码云代码提交记录

原文地址:https://www.cnblogs.com/DevilRay/p/6747132.html