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

    1. 本周学习总结

    • 1.1 以你喜欢的方式(思维导图或其他)归纳总结异常相关内容。

      ①finally块:无论是否被捕获或执行异常一定会被执行。

      在try或catch中遇到return语句时,finally语句块将在方法返回之前被执行。

      ②抛出异常:必须声明方法可抛出的任何可查异常,即如果一个方法出现异常,要么用try-catch捕获,要么用throws子句声明将它抛出,否则会导致编译错误。
      ③若覆盖一个方法,则不能声明和覆盖方法不同的异常,声明的任何异常必须是被覆盖方法所声明异常的同类或子类。

    2. 书面作业

    本次PTA作业题集 异常
    • 1.常用异常

      题目5-1

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

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

      ①经常出现的异常:

      Arrayindexoutofboundsexception:数组下标越界

      Nullpointerexception:程序遇上了空指针",简单地说就是调用了未经初始化的对象或者是不存在的对象

      ClassCastException:类型强制转换异常

      FileNotFoundException

      IllegalArgumentException:方法的参数错误

      ②RuntimeException是java设计中所有方法都默认定义在throws中了,所以只要你不捕获,就会一层一层的往上抛出RuntimeException的子类异常在源程序中可以不进行捕获和处理。上述异常中,FileNotFoundException属于checked Exception,需要捕获。其它皆是RuntimeException的子类,属于unchecked Exception,不需要捕获。
      除非你显示的标准要捕获它。否则不会被捕获。也不会造成编译异常。

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

      除了runtimeException以外的异常,都属于checkedException,它们都在java.lang库内部定义。程序必须用try-catch捕获或声明抛出这种异常。

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

      题目5-2

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

    • #######2.2 实验总结
      在5-2题中,当我们将非整型字符串输入int数组中时,出现的异常是NumberFormatException(字符串转换为数字异常),我们将这个异常捕捉并重新输入。注意i需要减一,否则不是重新输入,而是输入到下一个中。关键代码如下:

          for(int i=0;i<n;i++){
                	try{
                		str[i]=Integer.parseInt(input.next());
                	}catch(NumberFormatException e){
                		System.out.println(e);
                		i--;
                	}
      
    • 3.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");
            }
        
            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为十进制数字字符。

      第二种:参数s为数字字符串,参数radix为基数就是几进制。使用第二个参数指定的基数,将字符串参数解析为有符号的整数。

      ②该方法使用中可能会出现NumberFormatException,原因可能是:

      • 输入进制小于2或者大于36;
      • s为空;
      • s为数字字符串;

      4.函数题

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

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

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

      若try中的代码可能产生多种异常则可以对应多个catch语句,多个catch在通常情况下只会执行一个catch。 catch里的代码会顺序执行若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关闭资源。
      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 {
      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) {
      byte[] content = null;
      Scanner input=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.重点考核:使用异常改进你的购物车系统

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

      问题一:当将选择的商品加入购物车的时候需要输入购买数量,购买者可能会不小心输入非数字字符串。我们需要捕获此类异常。

        try{    String in=numjTextField.getText();
        		int num=Integer.parseInt(in);
        		Cart e = new Cart(books[flag1].getName(), books[flag1].getPrice(),num);
        		carts.add(e);}catch(NumberFormatException e){
        						 JOptionPane.showMessageDialog(null, "输入错误");
        					}
      用异常改进后,当输入错误内容的时候,会显示:
      

      问题二:当库存不足的时候,无法加入购物车。需要改进,当库存数量小于想要购买的数量的时候,提示错误信息。添加的改动如下(还没在图形界面运行):

        class ReserveException extends Exception{
        	public ReserveException(String thing){
        		super(thing);
        	}
        }
      
        	public void add(Cart e) throws ReserveException{
        	       if(e.getNum()>e.getNums()){
        	           throw new ReserveException("库存不足");
        	       }
      
    • 8.选做:课外阅读写出读后感

      JavaTutorial中Questions and Exercises

      Questions and Exercises

      Questions

      	try {
      	    
      	} finally {
      	    
      	}
      

      是合法的,try-finally语句中,finally语句块总是在控制权离开try语句块时执行的。无论try语句块是正常结束的,还是意外结束的,情况都是如此。

      8.2What exception types can be caught by the following handler?
      catch (Exception e) {
           
      }
      

      What is wrong with using this type of exception handler?

      所有类型的异常都将被捕获,因为Exception是所有异常类的父类。缺点就是对待不同的异常有相同的处理。

      8.3 Is there anything wrong with the following exception handler as written? Will this code compile?
      try {
      
      } catch (Exception e) {
          
      } catch (ArithmeticException a) {
          
      }
      

      ArithmeticException是Exception的子类,异常均在第一个catch中被捕获,第二个catch无法用到,正确方法是把子类异常放在前面,父类异常放在后面

      8.4 Match each situation in the first list with an item in the second list.

      a.int[] A;
      A[0] = 0;

      b.The JVM starts running your program, but the JVM can't find the Java platform classes. (The Java platform classes reside in classes.zip or rt.jar.)

      c.A program is reading a stream and reaches the end of stream marker.

      d.Before closing the stream and after reaching the end of stream marker, a program tries to read the stream again.

      1. b error

      2. d checked exception

      3. a compile error

      4. c no exception

    3. 码云上代码提交记录

    题目集:异常

    3.1. 码云代码提交记录

    4. 课外阅读

    Best Practices for Exception Handling
    Exception-Handling Antipatterns Blog
    The exceptions debate

  • 相关阅读:
    Java基础课程---将一个字符串反转,将字符串中指定部分进行反转,比如,"abcdefg", 反转为"abfedcg"
    在Centon64位中卸载安装时系统自带的--openjdk,并且安装自己需要的jdk
    Java基础课程---sleep()方法 和 wait()方法的异同(面试题)
    Java基础课程---权限修饰符
    Java基础课程---
    MySQL 创建库
    brew
    android webview load 本地文件需要注意的地方
    android下隐藏标题栏
    android webview无法加载网页
  • 原文地址:https://www.cnblogs.com/ballonbaby/p/6747873.html
Copyright © 2011-2022 走看看