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

1. 本周学习总结

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

  • java异常继承架构

2. 书面作业

本次PTA作业题集异常

1. 常用异常

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

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

ArrayIndexOutOfBoundsException判断数组下标是否越界抛出的异常。ClassCastException判断类型转换是否出错抛出的异常。NullPointerException判断需要对象的地方是否为null抛出的异常。IllegalArgumentException判断传入方法的参数是否合法或正确抛出的异常。

以上四个异常都为RuntimeException异常类的子类,RuntimeException异常类是Unchecked Exception(无须捕获),一般是对API的误用,无需try-catch。在编写程序时要注意尽量不要出现这些异常,比如在用户输入时,提示输入范围等说明。

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

当异常类是Exception的子类且非RuntimeException类时,需要进行Checked Exception捕获,需要使用try-catch或者throws说明异常发生时的处理情况,编译器会检查是否对异常进行处理。

  • 异常类的继承关系如图所示:

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

题目5-2
2.1 截图你的提交结果(出现学号)

2.2 实验总结

了解了Integer.parseInt(String str)方法,该方法能够将数字型字符串转化为整型,如果该字符串类型不满足要求,则会抛出NumberFormatException异常。当出现异常时,需要i--,满足数组中的元素都为满足要求的整型元素。了解了Arrays.toString(arr[] arr)方法,能够遍历输出数组元素。

3. throw与throws

题目5-3
3.1 截图你的提交结果(出现学号)

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

  • Integer.parsetInt源代码如下
    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");//如果传入的字符串为空,则抛出异常,提示null。
        }

        if (radix < Character.MIN_RADIX) {//Character.MIN_RADIX=2
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }

        if (radix > Character.MAX_RADIX) {// Character.MAX_RADIX=36
            throw new NumberFormatException("radix " + radix +
                                            " greater than Character.MAX_RADIX");//采用parseInt(String str)默认radix为10(表示最后转化为十进制),不会抛出这两个异常。
        }

        int result = 0;//初始数字字符串的值为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);//对于给定的基数,假如是合法的字符(可以转化为数字),返回该数字值,否则返回-1
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                if (result < multmin) {//判断有无溢出
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {//判断加上最后一位digit有无溢出
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
        } else {
            throw NumberFormatException.forInputString(s);//字符串为空
        }
        return negative ? result : -result;//转换成功,返回最后的结果
    }

4. 函数题

题目4-1(多种异常的捕获)
3.1 截图你的提交结果(出现学号)

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

如果多种异常中有父类子类的关系,需要将子类异常放在前面。这样当出现子类异常时,避免捕获成父类异常,从而达到我们捕获子类异常的目的。在eclipse中,若将父类异常放在子类异常前面会提示编译错误。

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

  • 红线部分出现以下提示,需要throws异常或try-catch。

  • 根据提示信息,进行try-catch,注意一些变量的初始化。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;

public class Main037 {

	public static void main(String[] args) throws IOException{
		byte[] content = null;
		FileInputStream fis = null;
		try{
			fis = new FileInputStream("testfis.txt");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}finally{		 
			if(fis==null)
				fis.close();
		}
		int bytesAvailabe = 0;
		try {
			bytesAvailabe = fis.available();
		} catch (IOException e) {
			e.printStackTrace();
		}//获得该文件可用的字节数
		if(bytesAvailabe>0){
			content = new byte[bytesAvailabe];//创建可容纳文件大小的数组
			try {
				fis.read(content);
			} catch (IOException e) {
				e.printStackTrace();
			}//将文件内容读入数组
		
		 }
		 
		 System.out.println(Arrays.toString(content));//打印数组内容
			
		
	}

}

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

  • 在try后面圆括号写上尝试自动关闭资源的对象生成
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

public class Main037 {

	public static void main(String[] args){
		byte[] content = null;
		FileInputStream fis = null;
		try (Scanner sc=new Scanner(new FileInputStream("testfis.txt"))){
			fis = new FileInputStream("testfis.txt");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		int bytesAvailabe = 0;
		try {
			bytesAvailabe = fis.available();
		} catch (IOException e) {
			e.printStackTrace();
		}//获得该文件可用的字节数
		if(bytesAvailabe>0){
			content = new byte[bytesAvailabe];//创建可容纳文件大小的数组
			try {
				fis.read(content);
			} catch (IOException e) {
				e.printStackTrace();
			}//将文件内容读入数组
		
		 }		 
		 
		 System.out.println(Arrays.toString(content));//打印数组内容
			
		
	}

}

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

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

  • 问题1;之前未考虑用户名为空的情况,这次在以前的基础上自定义抛出异常

  • 解决:当输入的用户名为空时,抛出异常并显示提示信息

public class Perinformation {
	
	String username;
	String password;
	public Perinformation(String username,String password){
		if(username.length()==0){
			throw new NullPointerException("用户名不能为空~");
		}
		this.username=username;
		this.password=password;
	}
	public Perinformation(){
		
	}
	public String toString() {
		return "Perinformation [username=" + username + ", password=" + password + "]";
	}
}
  • 问题2;将商品信息放在Goods.txt文档中,运行程序时导入文档信息,并将信息存入相应对象中,此时需要注意文件不存在的情况且最后要关闭资源。

  • 解决:当导入的文件名不存在时,抛出异常。

Goods[] book=new Books[2];
FileInputStream fileInputStream = null;
Scanner sc = null;
try {
	fileInputStream = new FileInputStream("Goods.txt");
	sc = new Scanner(fileInputStream);
	if(sc.hasNextLine()) {
		 book[0]=new Books(sc.nextLine(),sc.nextDouble(),sc.nextLine());
		 book[1]=new Books(sc.nextLine(),sc.nextDouble(),sc.nextLine());
	}
}catch(FileNotFoundException e) {
	 e.printStackTrace();
}finally{
    if(sc==null)
	sc.close();
}

7. 选做:JavaFX入门

完成其中的作业3。内有代码,可在其上进行适当的改造。建议按照里面的教程,从头到尾自己搭建。

8. 选做:课外阅读

JavaTutorial中Questions and Exercises

3. 码云上代码提交记录

题目集:异常

3.1. 码云代码提交记录

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

4. 课外阅读

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

posted @ 2017-04-22 16:06  卟噜卟噜  阅读(194)  评论(0编辑  收藏  举报