201521123072《java程序设计》第九周总结

201521123072《java程序设计》第九周总结

1. 本周学习总结

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

2. 书面作业

常用异常

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

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

在上面的图中,除开RuntimeException,Error及其子类的是不需要捕获的,属于Unchecked Exception ,其他的异常都是要捕获的
以前在编码时遇到的最多的就是数组越界,空指针问题,这些事不需要捕获的,因为其属于RuntimeException
我们可以通过加入一些判断语句来避免异常的产生

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

除开RuntimeException,Error及其子类,其他都需要捕获

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

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

2.2 实验总结

Integer.parseInt(str);将整型字符串转换成整型

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
    {
        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为例:在找出一组数中最大的值的函数中,如果输入的开始位置<0,则输出begin<0,
如果输入的开始位置>=结束位置,则输出begin>end
如果输入的结束位置>给定数组的长度,则输出:end>arr.length
代码如下:

                    if(begin<0)
				throw new IllegalArgumentException("begin:"+begin+" < 0");
			else if(end>arr.length)
				throw new IllegalArgumentException("end:"+end+" > arr.length");
			else if(begin>=end)
				throw new IllegalArgumentException("begin:"+begin+" >= "+"end:"+end);

函数题

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

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

catch块中的异常不得有继承关系

为如下代码加上异常处理

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) {
		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(IOException e){
			System.out.println(e);
		}
		finally
        {
			if(fis!=null){
				 try {
						fis.close();
					} catch (IOException e) {
						System.out.println(e);
					}
			}    
        }
		System.out.println(Arrays.toString(content));//打印数组内容
	}

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

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

重点考核:使用异常改进你的购物车系统

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

该输入数字必须为1-4之间,所以对 choose=Function.nextInt()该句进行try-catch()
关键代码:

 int choose=0;
		while(true){ 
			 try{  
				  choose=Function.nextInt(); 
				  if(choose<0||choose>4)
						throw new InputMismatchException("plese input agian:(1<=input<=4)"); 
					else 
						break;  
			 }catch(InputMismatchException e){ 
				 System.out.println("plese input agian:(1<=input<=4)");
				 String temp=Function.next();
			 }		
		 }

2.在读入文件的时候,可能会出错,读入的文件为空

改正为:

public static Object readObjectFromFile(String name)
    {
        Object[] temp=null;
        FileInputStream fils=null;
        try {
           fils= new FileInputStream(name);
            ObjectInputStream objIn=new ObjectInputStream(fils);
            temp=(Object[]) objIn.readObject();
            objIn.close();
            
        } catch (IOException e) {
            System.out.println("read object failed");
            
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        finally{
        	if(fils!=null){
				 try {
						fils.close();
					} catch (IOException e) {
						System.out.println(e);
					}
        }
        }
        return temp;
    }

选做:JavaFX入门

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

选做:课外练习

JavaTutorial中Questions and Exercises
练习总结

3.码云上代码提交记录

题目集:异常

3.1. 码云代码提交记录

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

posted @ 2017-04-22 14:29  七悸  阅读(261)  评论(0编辑  收藏  举报