201521123005 《Java程序设计》 第九周学习总结

1. 本周学习总结##

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

2. 书面作业##

本次PTA作业题集异常

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

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

答:以前编写的代码经常出现异常就是数组越界和访问空指针了。

1.数组越界:ArrayIndexOutOfBoundsException
从截图上看ArrayIndexOutOfBoundsException is-a RuntimeException,而该类异常由系统检测, 用户无需使用try catch进行捕获处理,系统将它们交给缺省的异常处理程序。所以我们应改进代码,比如不让数组下标越界,即检测数组下标是否越界来避免异常。

2.访问空指针:NullPointerException
从截图上看从截图上看ArrayIndexOutOfBoundsException is-a RuntimeException,所以无需使用try catch进行捕获处理。所以我们应改进代码,应先判断str是否为空或者编程的时候就要保证str指向一个实际存在的对象,来避免空指针的异常。

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

除了Error与RuntimeException及其子类以外的异常代码中必须try-catch来捕获异常。

2.处理异常使你的程序更加健壮
题目5-2
2.1 截图你的提交结果(出现学号)

2.2 实验总结

总结:Integer.parseInt(String)如果字符串不包含可解析的整数则抛出NumberFormatException,为了让程序更健壮,即在输入不包含可解析的整数的字符串,如“a",时,不让程序崩溃,而是提示你错误并且程序还可以继续运行。我们就要使用try-catch来捕获异常。这题它捕获异常后还要重新输入,只需在catch里加上i- -即可。
 try{
    x[i] = Integer.parseInt(inputInt);  
}catch(NumberFormatException e)
        {
	     System.out.println(e);//输出是什么异常和异常的原因
	      i--;//异常后可以重新输入
	 }

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

        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;
    }
阅读源代码后,我们可以知道首先要throws异常,然后具体的异常throw不同异常原因。即抛出异常时,应让用户知道错误发生的原因。那3-1题目当例子当arr数组越界则抛出ArrayIndexOutOfBoundsException异常则显示,当发生空指针,产生NullPointerException,当String对象强制转化为Integer对象,产生ClassCastException。当输入字符,转化为Integer,如果抛出NumberFormatException异常则显示。对不同的异常抛出不同的显示,且显示异常类及异常的具体原因,可以让调用者方便知道异常的原因,及时修改。

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

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

答:当一个异常被try块中的一个方法调用所抛出时,catch块以书写的顺序依次检查异常的类型,直到有一个匹配为止。拿我们上课的代码来说。
例:
try{
    System.in.read();
}
catch(IOException e){e.printStackTrace();}
catch(Exception e){e.printStackTrace();} 
如果IOException异常被抛出,那么控制就转移到第一个catch块;而如果Exception异常被抛出,控制就转移到第二个catch块。
例:
try{
    System.in.read();
}
catch(Exception e){e.printStackTrace();}
catch(IOException e){这里的代码永远不会被执行!!!} 
产生编译错误!

因为异常匹配的过程只是看异常对象是否属于catch所要捕捉的类型。既然所有的的异常都是Exception类的子类,这个catch就会捕捉到任何异常。所以第二个catch块永远不会被执行。
由于匹配过程的特点,在一个try语句中的各个catch块的顺序是有意义的。因为前面的父类的catch块在子类的catch块做匹配检查之前一定会匹配到子类的异常对象。所以子类异常必须放在父类异常前面。

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 改正代码,让其可正常运行。注意:里面有多个方法均可能抛出异常

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

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

		public static void main(String[] args) throws IOException {
			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(FileNotFoundException e){System.out.println(e);}
			catch(IOException e){System.out.println(e);}
			System.out.println(Arrays.toString(content));//打印数组内容
		}

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

一、
1.问题:从购买者输入到文件里的购买数量,有可能输入的是不包含可解析的整数的字符串。
2.解决方案:
    	String a=sumjTextField.getText();
    	try{
    	int b=Integer.parseInt(a);
           Cart e = new Cart(clothes.getName(), clothes.getPrice(), clothes.getNum(),b);
							carts.add(e);
    	}
    	catch(NumberFormatException ex){System.out.println(ex);
    		
    	}
二、
1.问题:购物车结算时,从文件获取信息,进行结算。这过程有可能遇到找不到文件的问题,文件中存在不包含可解析的数的字符串的问题,和是否关闭资源的问题
2.解决方案:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    double sum=0.0;
    FileReader reader = null;
	BufferedReader br =null;
	try{
		reader = new FileReader("shopping.txt");
		br = new BufferedReader(reader);
        String str1 = null;
        String str2=null;
        while((str1 = br.readLine()) != null) {
             str2=br.readLine();
             sum+=Double.valueOf(str1)*Double.valueOf(str2);
        }
	}
	catch(FileNotFoundException e){System.out.println(e);}
	catch(IOException e){System.out.println(e);}
	finally
	{
		if(reader!=null)
			try{
				reader.close();
			}
		catch(Exception e){System.out.println(e);}
		if(br!=null)
		try
		{
			br.close();
		}
		catch(IOException e){System.out.println(e);}
	}	
        sumjLabel.setText(" "+sum);        // TODO add your handling code here:
    
    }               

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

原文地址:https://www.cnblogs.com/yangxy/p/6731801.html