201521123025<<java程序设计>>第9周学习总结

本文探讨了异常处理的重要性,包括常见异常类型、如何通过捕获异常增强程序健壮性、throw与throws的区别,以及如何使用异常改进实际应用如购物车系统的案例。

1. 本周学习总结

1109884-20170422151236212-1290482709.png

2.书面作业

Q1.常用异常

题目5-1

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

1109884-20170422105305337-1171562102.png

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

经常出现ArrayIndexOutOfBoundsException(数组访问越界),不需捕获,因为该类异常属于RuntimeException。通过检测数组下标是否越界来避免,例如用if语句判断下标。

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

除了Error与RuntimeException及其子类以外的异常都是Checked Exception,也就是需要用户捕获处理try-catch

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

题目5-2

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

1109884-20170422110515806-619972314.png

2.2 实验总结

这题要求捕获输入非整型字符串异常,我原来是for(int i=0;i<arr.length;i++)按输入样例i=2时a[2]=a,a被捕获,但i继续加1,变成a[3],这样导致a[2]没被赋值。改成for(int i=0;i<arr.length;),然后在try{a[i]=;i++}catch(),这样输入整型就会执行一次i++,输入非整型字符串时会跳过i++,从而避免遗漏。

Q3.throw与throws

题目5-3

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

1109884-20170422125654431-1572448123.png

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

如果发生以下任意一种情况,则抛出一个 NumberFormatException 类型的异常:
1.第一个参数为 null 或一个长度为零的字符串。
2.基数小于 Character.MIN_RADIX 或者大于 Character.MAX_RADIX。
3.假如字符串的长度超过 1,那么除了第一个字符可以是减号 '-' ('u002D’) 外,字符串中存在任意不是由指定基数的数字表示的字符。
4.字符串表示的值不是 int 类型的值。

Q4.函数题

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

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

1109884-20170422135627837-2142863210.png

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

要注意(1)子类异常必须放在父类异常前面
(2)catch块中的异常不得有继承关系

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

import java.util.*;
import java.io.FileInputStream;
import java.io.IOException;
public class Main051 {

    public static void main(String[] args) throws IOException{
        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(Exception e){
                System.out.println(e);
        }finally{
            if(fis!=null){
              try{
                    fis.close();
            }catch(NullPointerException e){//判断是否是空指针异常
                        System.out.println(e);
            }
                }
        }
        System.out.println(Arrays.toString(content));//打印数组内容
    }

}

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

import java.util.*;
import java.io.FileInputStream;
import java.io.IOException;
public class Main052{
    public static void main(String[] args) throws IOException{
    byte[] content = null;
    try(FileInputStream fis = new FileInputStream("testfis.txt")){//在try的圆括号中写入将要关闭资源的对象
    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.重点考核:使用异常改进你的购物车系统(未提交,得分不超过6分)

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

问题:在输入商品数量时可能会出错,比如输入负数,或者超过最大购买量,或者输入字符等,希望能让用户知道输入出错的原因。

解决:

class Thenumber{
    public static double number(double n)throws IllegalArgumentException{
        if(n<0){
            throw new IllegalArgumentException("number:"+n+"<0");
        }
        if(n>999){
            throw new IllegalArgumentException("number:"+n+">999");
        }
        return n;
    }

}
public class Main {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        while(true){
        int num;
        String str=sc.next();
        try{
            num=Integer.parseInt(str);
            System.out.println(Thenumber.number(num));
            
        }catch(Exception e){
            System.out.println(e);
        }       
        }   
    }
}

1109884-20170422182314274-1915626826.png

3. 码云上代码提交记录

3.1. 码云代码提交记录

1109884-20170422152848556-1815880685.png

转载于:https://www.cnblogs.com/myfist/p/6747051.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值