java第九次学习总结

1. 本周学习总结

2.. 书面作业

1.常用异常 题目5-1

1.1 提交结果(出现学号)

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

以前编写的代码经常出现异常就是数组越界和访问空指针,不需要捕获,因为他们属uncheckExceotion.可以在编写代码的时候多注意一点避免出错。

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

除了RunTimeEcception以外的异常都需要捕获处理。

题目5-2

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

2.2 实验总结

因为这题在输入非数字时候会出现异常捕获,程序会继续运行。所以需要在输入非数字时,要i- -。

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

由Integer.parsetInt源代码可知,Integer.parsetInt(String s)当用户输入的不为整数时就会抛出NumberFormatException,并告知用户输入的哪一个值产生了错误。在5-3试验中,用户需要依次输入数组长度,对数组进行赋值,然后输入起始位置begin和终止位置end,结果输出begin~end的最大值,如果输入的参数不合法,即不符合上述条件,就会抛出相应异常并被捕获,同时告知用户参数不合法的具体原因,让用户及时有效的改正输入。

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

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

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

捕获时父类的异常应该放在子类异常的后面。

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

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 class test {
public static void main(String[] args) {
    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) {
        e.printStackTrace();
    } finally {
        // TODO: handle finally clause
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
}

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

public static void main(String[] args) throws IOException {
    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) {
        e.printStackTrace();
    }
} 

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

第一种情况是购物车提交物品数量不正常时出现异常

class ShoppingCart {
   ArrayList<Stuff> shoppingList=new ArrayList<Stuff>();
   ArrayList<Stuff>purchaseList=new ArrayList<Stuff>();
   public void add(Stuff e){
     try{
       int e.num=sc.nextInt();
     catch(Exception x)
       {
           System.out.println(x);
           System.out.println("所选商品数量必须是大于0的整数,请重新选择.");
       }
   }

第二种情况是确认购买时,输入true or false的其他字符出现异常。

System.out.println("请你确认是否购买该物品,确定购买输true,不买输入false。");
 try{
       boolean xy=sc.nextBoolean();
   }catch(Exception e){
        System.out.println(e);
   }                
  1. 码云上代码提交记录

题目集:异常

3.1. 码云代码提交记录

在码云的项目中,依次选择“统计-Commits历史-设置时间段”, 然后搜索并截图
选做:4. 课外阅读

任选下面一篇文章阅读,列举出几点自己能理解的异常处理最佳实践。

原文地址:https://www.cnblogs.com/lsl321/p/6747623.html