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

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

(1)使用try...catch语句捕获异常(try块后可跟一个或多个catch块,注意子类异常要放在父类异常前面,否则子类异常永远不会被执行到,编译器也会报错)
(2)java异常继承结构:Error(严重错误,如JRE内部错误,资源耗尽等,属于Unchecked Exception(无需捕获);Exception: RuntimeException(该类异常由系统检测,用户无需try...catch,属于Unchecked Exception)、其他Exception(该类异常受编译器检查,需要用户使用try...catch对异常进行处理,属于Checked Exception)
(3)常见异常:ArrayIndexOutOfBoundsException(数组下标越界异常)、NullPointerException(空指针异常)、ClassCastException(强制转换异常)、FileNotFoundException (文件不存在异常)、IllegalArgumentException(非法参数异常)
(4)finally语句:无论如何都会被执行到的语句,经常使用finally来释放资源。
(5)throws与throw:使用throws关键字声明方法中可能会出现的异常,而throw语句用来抛出异常
2. 书面作业

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

1.2 自己以前编写的代码中经常出现什么异常、需要捕获吗(为什么)?应如何避免?
答:以前编写的代码中经常出现ArrayIndexOutOfBoundsException,NullPointerException,ClassCastException,IllegalArgumentException等异常,不需要捕获,因为它们都是运行时异常,运行时异常无需捕获。出现运行时异常一般来说是由于编码失误如误用API,我们应该尽量改进代码避免出现此类错误。
1.3 什么样的异常要求用户一定要使用捕获处理?
答:除了RuntimeException及其子类以外,其他的Exception类及其子类异常要求用户一定要使用捕获处理。
Q2.处理异常使你的程序更加健壮
题目5-2
2.1 截图你的提交结果(出现学号)

2.2 实验总结
实验总结:将字符串转换成有符号的十进制整数,由于字符串可能为非整型字符串,所以可能出现NumberFormatException ,所以要对该异常进行捕获,捕获的同时要求用户重新输入,我们可以将计数器进行自减操作即可实现。

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

答:将字符串参数作为有符号的十进制整数进行解析,parseInt方法只抛出NumberFormatException这种异常,抛出异常时传递给调用者错误发生的原因。如:(1)字符串参数指向为null(2)进制数小于最小进制数2(3)进制数大于最大进制数36(4)字符串的第一个字符不是数字,也不是正负号(5)字符串为正号或负号(6)字符串为""
Q4.函数题
题目4-1(多种异常的捕获)
4.1 截图你的提交结果(出现学号)

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

答:一个try块中如果可能抛出多种异常,捕获时注意子类异常要放在父类异常前面。
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关闭资源。
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);//将文件内容读入数组
}
System.out.println(Arrays.toString(content));//打印数组内容
}
catch(IOException e){
System.out.println(e);
}
finally{
if(fis!=null){
fis.close();
}
}
}
5.2 使用Java7中的try-with-resources来改写上述代码实现自动关闭资源.

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);//将文件内容读入数组
}
System.out.println(Arrays.toString(content));//打印数组内容
}
catch(IOException e){
System.out.println(e);
}

}

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

(1)从文件中读取商品信息时可能会碰到文件不存在的情况,此时若不对该异常进行捕获,程序就会崩溃。

public static void main(String[] args)throws FileNotFoundException {
Scanner scanner=null;
ArrayListstuff=new ArrayList();
try{

        scanner=new Scanner(new FileInputStream("D:\\list.txt"));
        while(scanner.hasNextLine()){
            String str=scanner.nextLine();
            String []str1=str.split(" ");
            stuff.add(new Stuff(str1[0],Integer.parseInt(str1[1]),str1[2],Integer.parseInt(str1[3]),str1[4]));
        }
    }
    catch(FileNotFoundException e){
        System.out.println(e);
    }
    finally{
        if(scanner!=null)
            scanner.close();
        
    }

}
(2)当商品的数量为0时无法将其添加至购物车,抛出异常(自定义异常)

class CannotbeAddToCartException extends Exception {

public CannotbeAddToCartException(String str){
    super(str);
}

}
public void add(Stuff e) throws Exception{
if(e.Num==0){
throw new CannotbeAddToCartException("商品库存不足无法添加至购物车");
}

}
public static void main(String[] args)throws Exception {
System.out.print("请输入商品名:");
String str = s.next();
try{
sh.add(Stuff.search(str, stuff));
}
catch(Exception e){
System.out.println(e);
}
}
3. 码云上代码提交记录
题目集:异常

3.1. 码云代码提交记录

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

posted on 2017-04-22 20:28  我信了你的邪  阅读(129)  评论(1编辑  收藏  举报