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

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

标签(空格分隔):java


1.本周学习总结

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


2. 书面作业

本次PTA作业题集异常

1.常用异常

题目5-1

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

Answer:


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

Answer:
通常Exception可分为Checked Exception 和 Unchecked Exception。
如下常见的Unchecked Exception:

在大一学习高级语言以来遇到最多的异常还是Unchecked Exception。我觉得Unchecked Exception 是不需要捕获的,比如最常见的数组越界,我们平时在输入的时候注意一下就好了。我觉得Unchecked Exception 可以在程序源码中加入比如if的判断语句来保证输入的正确性,既可以减少捕获又保证不出现异常。


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

Answer:
Checked Exception要求用户一定要使用捕获处理。除了Error与RuntimeException及其子类以外的异常都是Checked Exception。我们可以通过try-catch和throws方法来处理异常。

扩展学习:Java 异常处理的误区和经验总结


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

题目5-2

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

Answer:


2.2 实验总结

Answer:
题目2要求使用异常机制处理异常输入,其实较题目1来说还是相对比较简单的。首先实例化一个数组,然后循环输入数据,用try-catch来实现当输入的是非整型字符串提示异常。


3.throw与throws

题目5-3

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

Answer:


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

Answer:
先贴上源码:

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

结合3.1,就是运行程序后需要使编译器对这段代码抛出什么异常及原因反馈给使用者,让使用者及时更改。比如,3.1中输入 0 6时,应该及时抛出ArrayIndexOutOfBoundsException说明数组越界,让读者明白输入的范围,简单明了。


4.函数题

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

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

Answer:


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

Answer:

  • 处理多种异常不同时,注意Exception子类的异常处理要放在父类的异常处理之前,否者子类的异常是处理不到的。
  • 处理多种异常都相同时,可以使用catch(Exception e){}。

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 改正代码,让其可正常运行。注意:里面有多个方法均可能抛出异常

Answer:
1.首先不存在testfis.txt,FileInputStream()方法会抛出FileNotFoundException异常。
2.available()和read()都会抛出IOException异常。
修改如下:


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

Answer:


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

举至少两个例子说明你是如何使用异常机制让你的程序变得更健壮。
说明要包含2个部分:1. 问题说明(哪里会碰到异常)。2.解决方案(关键代码)
Answer:
1.一个最简单的例子,比如我选择了一样商品后,会提示添加的商品的数量,如果输入的数据为非整形,则会抛出InputMismatchException异常。

System.out.println("请输入需要的商品数量:");
		try {
			num = input.nextInt();
		} catch (InputMismatchException e) {
			System.out.println(e);
		}


2.还有一个例子,就是从本地读入商品信息时,如果本地的文件不存在,应该提示异常:
如下运行结果:
txt存在时:


txt不存在时:


7.选做:JavaFX入门

如果未完成作业1、2的先完成1、2。贴图展示。如果已完成作业1、2的请完成作业3。内有代码,可在其上进行适当的改造。建议按照里面的教程,从头到尾自己搭建。
Answer:
逐步完善如下:




8.选做:课外阅读

JavaTutorial中Questions and Exercises
Answer:

Questions and Exercises

1.Is the following code legal?
try {

} finally {

}
Answer:合法。

原文的解析:try并不一定要有一个catch块,也可以是一个finally块。每当有finally块,该代码必须始终被执行。这包括资源回收的代码,如关闭I / O流。


2.What exception types can be caught by the following handler?

catch (Exception e) {
}
What is wrong with using this type of exception handler?
Answer:可以捕获任何异常,但不能根据特定的异常做出相应的处理。


3.Is there anything wrong with the following exception handler as written? Will this code compile?

try {

} catch (Exception e) {

} catch (ArithmeticException a) {

}
Answer:
在第一个catch块就捕获Exception父类异常,如法捕获第二个子类异常。


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.__error
2.__checked exception
3.__compile error
4.__no exception
Answer:

  • a-3(编译错误)。数组没有初始化,将无法编译。
  • b-1(错误)。
  • c-4(无异常)。当你读一个流,你认为会有流标记的结束。你应该使用异常捕捉程序中的意外行为。
  • d-2(检查异常)。

3. 码云上代码提交记录

题目集:异常

3.1. 码云代码提交记录

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


选做:4. 课外阅读##

阅读网站:
The exceptions debate
个人收获:
C++和java都支持抛出异常,但java有分为checked exceptions和Unchecked exceptions,而这篇文章主要讨论异常要不要检查。文中主要对checked exceptions的部分缺点进行了阐述。比如代码的不可读性,举了一个三行代码和六个catch块的例子,代码十分臃肿。
由于英语水平有限,在后面更仔细阅读后再来补充。

原文地址:https://www.cnblogs.com/moyi-h/p/6747701.html