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

1. 本周学习总结

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

2. 书面作业

1.本次PTA作业题集异常

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

1.2 自己以前编写的代码中经常出现什么异常、需要捕获吗(为什么)?应如何避免?
A:以前编写的代码经常出现异常就是数组越界IndexOutOfBoundsException和非法数据异常IllegalArgumentException,属于Runtime Exception,无需使用try-catch进行捕获处理
1.3 什么样的异常要求用户一定要使用捕获处理?
A:除了Error与RuntimeException以外的异常要求用户一定要用try-catch来捕获异常

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

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

2.2 实验总结
A:使用Integer.parseInt(in.next())对数组进行输入赋值,这时若输入的不是数字,则容易出现NumberFormatException 异常,这时需要我们对它进行捕获

3.throw与throws

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

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

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将相对应的异常传递给调用者

4.函数题

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

4.2 一个try块中如果可能抛出多种异常,捕获时需要注意些什么?
A:Exception的子类异常不能在Exception后被catch。 如果用catch块,块中异常不得有继承关系;如果抛出多种异常来指示不同类型的问题,这些都是受检异常,必须都列在方法的throws子句中,它们之间以逗号分开

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

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

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

 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.解决方案(关键代码)
A:

String []b = in.nextLine().split(" ");
arr = new int[b.length];
for (int i = 0; i < arr.length; i++) {
  arr[i] = Integer.parseInt(b[i]);
				}
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
				
			}
try {
				if (str.equals("arr")) {
					int n = in.nextInt();
					arr[n] = n;
				} else if (str.equals("null")) {
					String str1 = null;
					str1.length();
				} else if (str.equals("cast")) {
					List<Object> str2 = new ArrayList<Object>();
					str2.add("a");
					Integer x = (Integer) str2.get(0);
					System.out.println(x);
				} else if (str.equals("num")) {
					String str3 = in.next();
					Integer.parseInt(str3);
				} else {
					break;
				}

			} catch (ArrayIndexOutOfBoundsException ex) {
				System.out.println(ex);
			} catch (NullPointerException ex) {
				System.out.println(ex);
			} catch (ClassCastException ex) {
				System.out.println(ex);
			} catch (NumberFormatException ex) {
				System.out.println(ex);
			}
		}

说明:容易出现数组越界问题,还有Next()和Nextline()的不同效果,所以语法上的运用也是很有讲究的

3. 码云上代码提交记录

题目集:异常

3.1. 码云代码提交记录

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

原文地址:https://www.cnblogs.com/wangyan12345/p/6747332.html