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

1. 本周学习总结##

2. 书面作业##

本次PTA作业题集异常

Q1.常用异常##

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

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

经常出现ArrayIndexOutOfBoundsException,IllegalArgumentException,EmptyStackException等,这些都是Unchecked Exception,不需要捕获,这只需要在提醒之后对原代码进行修正即可。注意需要输入的参数类型,在操作数组时注意数组长度。

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

当异常类是Exception的子类且非RuntimeException类时,需要进行Checked Exception捕获,必须受检即要捕获处理。

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

题目5-2
2.1 截图你的提交结果(出现学号)

2.2 实验总结

处理输入数组元素时,要考虑数组下标位置问题,在出现异常之后要i- -,不然在输入数组的长度后,如果后面输入出现异常,就会减少了整数的输入次数。

Q3:throw与throws##

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

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

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");//一开始就指明要抛出的异常,如果s为空,则抛出异常。
        }

        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;
    }

首先在Integer.parsetInt源代码的开头有语句throws NumberFormatException表明要抛出异常,抛出异常时需要给调用者传递输入的数组的大小,以及输入的开始与结束的位置,其次代码里还有使用if语句来抛出满足条件的异常。

Q4.函数题##

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

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

应该注意,子类异常要在父类异常的前面,否则将捕获不到子类异常,只能抛出父类异常。一段代码可能会抛出多个异常,需要写多个catch子句来捕获,而若是用多个catch块进行捕获,catch块中的异常不得有继承关系,否则会直接捕获而未进行下边的异常捕获

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) 
        byte[] content = null;
        try{
        FileInputStream fis = new FileInputStream("testfis.txt");
        int bytesAvailabe = fis.available();//获得该文件可用的字节数
        if(bytesAvailabe>0){
            content = new byte[bytesAvailabe];//创建可容纳文件大小的数组
            fis.read(content);//将文件内容读入数组
        }
        fis.close();
    }
    catch(FileNotFoundException e){
            System.out.println(e);
    }
    catch(IOException e){
            System.out.println(e);
    }
    catch(SecurityException e){
            System.out.println(e);
    }
        System.out.println(Arrays.toString(content));//打印数组内容
    }

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

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

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

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

eg.1 问题说明: 查询不到商品,抛出异常。
     解决方案:            
public class Product{
    private Product pro = new Product();
    public List<Product> findAll(){
        try {
            return pro.findAll();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
eg.2  问题说明:进行购物车的添加时,当所选择的商品出现数量为0时则无法添加,此时需要抛出提示该商品已售完
      解决方案:
ArrayList<Product> prolist = new ArrayList<Product>();
    public void addpro(Product pro){
        try{
        prolist.add(pro);
        }catch(NullPointerException e){
            System.out.println("该商品已售空"); 
        }
    }

3. 码云上代码提交记录##

题目集:异常
3.1. 码云代码提交记录
在码云的项目中,依次选择“统计-Commits历史-设置时间段”, 然后搜索并截图

原文地址:https://www.cnblogs.com/YYYYYYY/p/6748741.html