201521123113《Java程序设计》第9周学习总结

1. 本周学习总结

2. 书面作业

本次PTA作业题集异常

Q1.常用异常

题目5-1

1.1 截图你的提交结果(出现学号)

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

  • 经常出现IllegalArgumentException、ArrayIndexOutOfBoundsException、NullPointerException、ClassCastException、NumberFormatException等异常;
  • 这些异常都属于RuntimeException异常,不需要捕获。
  • 写代码时要注意各种语句的要求限制;例如对于一个数组,在对数组进行赋值时要注意数组的长度以及数组内对象的属性,避免ArrayIndexOutOfBoundsException异常出现。

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

  • 除了Error和RuntimeException外的异常,属于Checked Exception的异常都要进行捕获。

Q2.处理异常使你的程序更加健壮

题目5-2

2.1 截图你的提交结果(出现学号)

2.2 实验总结


    for(int i = 0; i < arr.length;){
        try{
            String inputInt = in.next();
            arr[i] = Integer.parseInt(inputInt);
            i++;
            }catch(Exception e){
                System.out.println(e);
}

  • 本题主要考察了对NumberFormatException 异常的捕获,对于arr数组,如果把i++这个语句放在try里面,就可以先判断输入是否为整型再向arr里加入inputInt,这样就不用考虑inputInt为非整型字符串后对arr下标的处理。

Q3.throw与throws

题目5-3

3.1 截图你的提交结果(出现学号)

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

Integer.parsetInt源代码如下:

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;
    }
  • 由上源代码可知,抛出异常时要告知调用者哪里出现问题;
  • 对于上源代码,输入的s为null、不可用于与字符串相互转换的基数、s为空、出现非整型字符串等情况要对调用者进行反馈错误信息。
  • 对于题5-3,要求输入的begin < end,begin >= 0,end <= arr.length,就要分别对着三个条件进行,代码如下:
	if(begin>=end)
		throw new IllegalArgumentException("begin:"+ begin +" >= "+ "end:"+end);
	if(begin<0)
		throw new IllegalArgumentException("begin:"+begin+" < 0");
	if(end>arr.length)
		throw new IllegalArgumentException("end:"+end+" > arr.length");

Q4.函数题

题目4-1(多种异常的捕获)

4.1 截图你的提交结果(出现学号)

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

  • 子类异常必须得放在父类异常后面,例如Exception的子类IOException异常不能放在Exception后面,否则会产生编译错误;

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关闭资源。

    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);//将文件内容读入数组
        }
        System.out.println(Arrays.toString(content));//打印数组内容 
    } catch (IOException e) {
        System.out.prientln(e);
    }
    finally{
          try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

    byte[] content = null;
    try(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));//打印数组内容
    }catch(IOException e){
    System.out.println(e);
}

Q6.重点考核:使用异常改进你的购物车系统(未提交,得分不超过6分)

举至少两个例子说明你是如何使用异常处理机制让你的程序变得更健壮。
说明要包含2个部分:1. 问题说明(哪里会碰到异常)。2.解决方案(关键代码)

1.例如:

  • 输入的为非整型,就会出现InputMismatchException异常错误,修改代码如下
	try{
		 num = in.nextInt();
	}catch(Exception e){
		System.out.println("输入有误,请重新输入");
		}
	}

3. 码云上代码提交记录

3.1. 码云代码提交记录

原文地址:https://www.cnblogs.com/leexd/p/6734413.html