zoukankan      html  css  js  c++  java
  • 201521123028 《Java程序设计》 第9周学习总结

    1. 本周学习总结

    2. 书面作业

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

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

    在JAVA中的常见异常:
    ArrayIndexOutOfBoundsException  数组越界
    NullPointerException            空指针
    ClassCastException              转换不兼容(强制转换)
    FileNotFoundException           系统找不到指定路径
    IllegalArgumentException        非法参数
    

    平时编程比较常见的异常是主要是ArrayIndexOutOfBoundsException(数组越界)、NullPointerException(空指针)和ClassCastException(强制转换异常)。
    而这些异常都属于RuntimeException。对RuntimeException,我们有如下定义:

    • 一般是对API的误用,无需try-catch
    • 程序员应改进代码,比如不让数组下标越界
    • 属于Unchecked Exception
      这个定义解决了这个问题,无需捕获(try-catch),通过改进代码避免

    1.3 什么样的异常要求用户一定要使用捕获处理?
    Ans:
    在Java的异常继承架构中,有如下异常:

    • Error:属于严重错误,程序员基本无法处理。
    • Exception:其中主要分为两类
      ①RuntimeException:在1.2中已经提到,属于Unchecked Exception,无需try-catch。
      ②Exception其他子类:属于Checked Exception,我们需要弄懂这个错误,必须try-catch处理。
      因此在Exception的其他子类中,我们需要捕获。

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

    2.2 实验总结
    根据题目要求,这题我们需要try-catch数组中的非整型异常,即NumberFormatException,使用try-catch对输入数组元素放入数组相关程序短进行NumberFormatException捕获即可。

    Q3.throw与throws
    题目5-3

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

    3.2 阅读Integer.parsetInt源代码,结合3.1说说抛出异常时需要传递给调用者一些什么信息?
    Ans:
    贴出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;
        }
    
        public static int parseInt(String s) throws NumberFormatException {
            return parseInt(s,10);
        }
    

    对应注释

    抛出异常时,应首先抛出给调用者异常,再抛出其原因,
    我们以Integer.parsetInt方法及其源代码为例,
    首先,Integer.parsetInt方法的主要作用是将字符串转化为整型数字,
    那么,当我们输入的字符并非一个一个数字,而是字母或者符号时,就会产生导致Integer.parsetInt方法无法作用的异常,即第二题中出现过的NumberFormatException
    那么此时就需要将其抛出。
    再观察Integer.parsetInt的源代码,

    此时抛出NumberFormatException这个异常,用户就清楚的知道自己刚才输入的并非整形数字,而是不符合要求的字符了。

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

    4.2 一个try块中如果可能抛出多种异常,捕获时需要注意些什么?
    Ans:
    子类的异常要在父类异常前进行捕获,例如4.1,
    若是父类Exception先于子类NumberFormatException和IllegalArgumentException被捕获,那么系统就会报错,产生编译错误。

    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关闭资源。
    Ans:
    题目所给代码无法正常运行,也就是说会报错,那么想要它正常运行,就需要弄清楚错在哪,因此我们直接复制粘贴题目所给代码,得到如下报错:

    报错显示异常FileNotFoundException和IOException没有得到处理。
    使用JDK文档对FileNotFoundException和IOException类进行了查询,惊奇的发现:

    FileNotFoundException类是IOException类的子类,那么就是说在Main函数中throws IOException,即可抛出没有得到处理的所有异常。
    因此,对程序做throws处理,得到

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.*;
    
    public class Main {
    	public static void main(String[] args)throws IOException {
    	    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));// 打印数组内容
    	    fis.close();
    	}
    }
    

    5.2 使用Java7中的try-with-resources来改写上述代码实现自动关闭资源.
    利用try-with-resources来改写上述代码实现自动关闭资源的办法:
    Java7中提供了自动尝试关闭资源的语法,可将尝试自动关闭资源的对象生成写在try之后的圆括号中

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.*;
    
    public class Main {
    	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);// 将文件内容读入数组
    	    }
    	    }
    	    catch(Exception e){
    	        System.out.println(e);
    	    }
    	    System.out.println(Arrays.toString(content));// 打印数组内容
    	}
    }
    

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

    3. 码云上代码提交记录

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

  • 相关阅读:
    给我30000出租车,还你一个不堵车的北京
    使用vim代替IDE
    (转)声明,函数与函数指针
    想恶作剧的请看过来
    bash命令提示符的更改
    (转)微软面试
    140个Google面试问题
    UTF8 GBK UTF8 GB2312 之间的区别和关系(转)
    MyBooksReadingStatic
    让SlickEdit 自动编译Keil C51工程
  • 原文地址:https://www.cnblogs.com/KILL-ljj/p/6746558.html
Copyright © 2011-2022 走看看