Paparazzi

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1. 本周学习总结#

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

  • 异常(Exception)处理
  • 异常(Exception)的概念:在程序运行的时候可能出错,Java中把程序出现的错误当作一种异常现象其用于出错处理的机制就是异常处理机制。
  • Java中使用try-catch语法处理异常
    try {
           可能产生异常的代码段
      }catch (ExceptionType e) {//捕获异常
    处理异常
}

Java是面向对象语言,在Java中
可以用异常对象来表示程序运行中碰到的错误!

  • 异常处理机制:
    发生错误时生成一个代表该错误的异常对象(包含出错的详细信息)
    JVM(Java虚拟机)发现该异常对象
    JVM寻找相应的代码来处理这一异常
    捕获(catch):找到该异常的处理代码
    抛出(throw):再次提交给JVM

  • Java异常继承架构:
    Error(严重错误):无需关心
    RuntimeException:无需try-catch
    Exception其他子类:必须try-catch处理

  • Java中常见的几个异常
    ArrayIndexOutOfBoundsException
    NullPointerException
    ClassCastException
    FileNotFoundException

  • finally与资源管理
    当程序代码发生异常时,抛出异常处之后的代码不会被执行
    如果在发生异常前程序开启了相关资源,那么有可能你的代码无法正确关闭资源
    无论try catch块有无发生异常,finally块中的代码一定会被执行

  • 异常的处理:throws与throw
    例子:
    public int read() throws IOException


2. 书面作业#

Q1 常用异常##

题目5-1

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

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

经常出现数组越界这个异常ArrayIndexOutOfBoundsException,例如定义数组int[] a=new int[5],int[5]=0;但不需要捕获,ArrayIndexOutOfBoundsException是属于RuntimeException,需要自己在代码里修改,平时写代码的时候要注意这个问题,例如在for语句中使用n<size

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

在Exception子类中,除去RuntimeException,其他子类都是check Exception,也就是要求用户一定要使用捕获处理的异常,都需要try-catch来捕获,如果不处理这些异常,则不能进行编译.

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

题目5-2

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

2.2 实验总结###

主要代码:try{
				arr[i]=Integer.parseInt(s);
				
			}catch(Exception e){
				System.out.println(e);
				i--;
			}
由于在输入"a"是捕获到异常,为了使数组正常,下标i需要-1;

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

将字符串参数作为带符号十进制整数来分析。这里的radix是基数,几进制的意思。除过第一个字符为 ASCII 字符中减号 '-' 表示的负数,字符串中的字符都必须是十进制数。如果不是则抛出NmberFormatException.抛出异常时应该告诉调用者异常的原因。5-3中抛出的是 IllegalArgumentException("end:"+end+" > "+"arr.length");表示的是end>arr.length.要求begin<end,要抛出相应的异常(IllegalArgumentException`)比如begin不得小于0,end不得大于arr.length,否则抛出异常。

Q4 函数题##

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

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

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

需要注意子类异常必须放在父类异常前面,如果父类异常放在前面,则会执行父类异常的捕获而不执行子类异常的捕获,导致编译错误。
例如:catch(Exception e){
    System.out.println(e);//执行,输出Exception异常的其它异常子类
}catch(ArrayIndexOutOfBoundsException e){
    System.out.println(e);//不会执行

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{
    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来改写上述代码实现自动关闭资源.###

Java7中提供了自动尝试关闭资源的语法,可将尝试自动关闭资源的对象生成写在try之后的圆括号中,无需判断是否为null,也避免了在关闭时产生的其它异常
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分)##

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

1.问题说明

商品的价格可能输入的不是Double型的字符串,转换时发生异常,NumberFormatException异常。
商品数量可能输入的不是Integer型的字符串,转换时发生异常,NumberFormatException异常。
商品名可能会是空的对象添加,NullPointerException异常
代码:

2.关键代码

 try{
    String[] strs = jTextField1.getText().split(" ");//可能会是空的对象添加,NullPointerException异常
    String name = strs[0];
    double price=Double.parseDouble(strs[1]);//可能输入的不是Double型的字符串,转换时发生异常,NumberFormatException异常
    Integer num =Integer.parseInt(strs[2]);//可能输入的不是Integer型的字符串,转换时发生异常,NumberFormatException异常
    Shop shop = new Shop(name,price,num);
    boolean flag = shopDao.save(shop);
    if(flag){
        JOptionPane.show(null, "添加成功");
    }else{
        JOptionPane.show(null, "添加失败!");
    }
    }catch(NumberFormatException e){
        System.out.println(e);
        System.out.println("输入的参数类型不符合 String Double Integer");
    }catch(NullPointerException e){
        System.out.println(e);
         System.out.println("输入的参数为空");
    }catch(ArrayIndexOutOfBoundsException e){
        System.out.println(e);
         System.out.println("输入的参数个数未符合3个");
    }catch(Exception e){
        System.out.println(e);
         System.out.println("其它的错误");
    }
    }                          

效果截图:


3. 码云上代码提交记录#

题目集:异常

3.1 码云代码提交记录##

posted on 2017-04-22 14:13  Paparazzi  阅读(216)  评论(4编辑  收藏  举报