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

    1. 本周学习总结

    1.1 思维导图如下:


    2. 书面作业

    本次PTA作业题集异常


    1. 常用异常

    题目5-1

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

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

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


    1.1 答:截图如下:

    1.2 答:ArrayIndexOutOfBoundsException(数组越界异常)还有NumberFormatException(数字格式异常)
    ArrayIndexOutOfBoundsException(数组越界异常)和NumberFormatException(数字格式异常)通过查阅jdk文档可以发现:数组越界异常和数字格式异常都间接继承了RuntimeException,而RuntimeException属于Unchecked Exception,都会由系统直接检测,不需要try-catch,避免的话,可以通过检查代码运行来修改代码以解决异常。

    1.3 答:除了ErrorRuntimeException及其子类的以外的都属于Checked Exception,需要用try-catch捕获来处理。


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

    题目5-2

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

    2.2 实验总结


    2.1 答:截图如下:

    2.2 实验总结:本题的关键在于Integer.parseInt(String s);语句,该语句作用:将字符串参数作为有符号的十进制整数进行解析。在该题中,若输入非整型字符串,会抛出NumberFormatException异常,可以用try-catch语句捕获NumberFormatException异常然后做出相应的处理,捕获异常后要重新输入,所有要在catch语句块中加一句i--即可。

    try{
        String strnumb = sc.next();
        array[i] = Integer.parseInt(strnumb);
    } catch (NumberFormatException e) {
        System.out.println(e);//输出异常信息
        i--;
    }
    

    3. throw与throws(题目5-3)

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

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


    3.1 答:截图如下:

    3.2 答: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可能抛出的异常,然后具体的异常会throw出不同异常原因。就是在抛出异常时,应让用户知道错误发生的原因。例如5-3题中当arr数组越界则会抛出ArrayIndexOutOfBoundsException异常,当发生空指针,抛出NullPointerException,当String对象强制转化为Integer对象,抛出ClassCastException。当输入字符,转化为Integer,如果抛出NumberFormatException异常则显示。对于不同的异常抛出不同的异常,在控制台中显示异常类及异常的具体原因,能够让调用者知道异常的原因,然后及时修改。


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

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

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


    4.1 答:截图如下:

    4.2 答:注意点:
    (1)、注意catch异常的先后顺序:子类异常必须放在父类异常前面;
    (2)、catch块中的异常不得有继承关系


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

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


    5.1 代码如下:

    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.Arrays;
    
    public class Main {
    
    	public static void main(String[] args) throws IOException  {
    		// TODO Auto-generated method stub
    		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 (FileNotFoundException e) {
    			System.out.println(e);
    		}catch (IOException 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 答:代码如下:

    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.Arrays;
    
    public class Main01 {
    
    	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(FileNotFoundException e){System.out.println(e);}
            catch(IOException e){System.out.println(e);}
    		System.out.println(Arrays.toString(content));//打印数组内容
    	}
    
    }
    

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

    举至少两个例子说明你是如何使用异常处理机制让你的程序变得更健壮。

    说明要包含2个部分:1. 问题说明(哪里会碰到异常)。2.解决方案(关键代码)


    1、问题说明:
    (1)、输入商品id后选择商品数量时如果输入不是int型数字会出现异常;
    (2)、当选择是否进入系统时如果输入不是整型数字会出现异常;
    2、解决方案:

    //(1)、
    try {
    	if (goods1.equals(goods[j].id)) {
    	    ShoppingCar s = new ShoppingCar(goods[j].goodsname,goods[j].price, goods[j].nature,goods[j].id, sc.nextInt());
                Car.add(s);
    	} else continue;
    } catch (InputMismatchException e) {
        System.out.println("商品数量输入错误!应输入正整数!!!");
        i--;
    }
    
    //(2)、
    try {
        int n = sc.nextInt();
        if (n == 0) {
            sc.close();
            return;
        }
    } catch (InputMismatchException e) {
        System.out.println(e);
    }
       
    

    3. 码云上代码提交记录

    题目集:异常

    3.1. 码云代码提交记录

  • 相关阅读:
    HSF原理
    Spring IOC 容器源码分析
    Spring Bean注册和加载
    CAP和BASE理论
    Java内存模型
    Java线程模型
    IO复用、多进程和多线程三种并发编程模型
    无锁编程本质论
    An Introduction to Lock-Free Programming
    安装与配置ironic
  • 原文地址:https://www.cnblogs.com/wjt960310/p/6747955.html
Copyright © 2011-2022 走看看