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

1. 本章学习总结

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

2. 书面作业

本次作业题集异常

  • Q1:常用异常
    题目5-1

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

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

答:经常出现如下几种异常
数组越界异常:

空指针异常:

强制转换异常:

以上几种异常均不需要捕获,由JDK截图可知,这三种异常都继承RuntimeException,所以无需捕获。要想避免这类异常,我们就应在编写程序的过程中注意数组边界、判断空指针、强制类型转换等问题。

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

答:除了ErrorRuntimeException异常类及其子类以外的异常,都要求用户一定要使用捕获处理,也就是Checked Exception

  • Q2:处理异常使你的程序更加健壮
    题目5-2

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

  • 2.2 实验总结

答:这题比较简单,老师在课上也说过。在for循环中进行try-catch捕获异常,需要注意的是在catch语块中输出异常后还要进行i--,否则会出错的。

  • Q3: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
        {
            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;
        }
> 由源码可知,当传入的字符串为null、radix < Character.MIN_RADIX等时,就会抛出NumberFormatException异常。在本题中,当`begin >= end`,`begin > 0`或`end > arr.length`时,抛出IllegalArgumentException异常,并且打印说明异常的原因。
  • Q4:函数题
    题目4-1(多种异常的捕获)

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

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

答:需要注意多种异常之间的继承关系,应先捕捉子类再捕捉其父类。
比如本题出现的NumberFormatExceptionIllegalArgumentExceptionException三种异常。
NumberFormatExceptionIllegalArgumentException的子类,IllegalArgumentExceptionException的子类,所以要按照NumberFormatExceptionIllegalArgumentExceptionException的顺序编写catch块。

  • 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 Exception {
		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)
				fis.close();
		}
		System.out.println(Arrays.toString(content));// 打印数组内容
	}
运行结果:

  • 5.2 使用Java7中的try-with-resources来改写上述代码实现自动关闭资源.
public static void main(String[] args) throws Exception {
		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 (Exception e) {
			System.out.println(e);
		}
		System.out.println(Arrays.toString(content));// 打印数组内容
	}
运行结果如上。
  • Q6:重点考核:使用异常改进你的购物车系统(未提交,得分不超过6分)
    举至少两个例子说明你是如何使用异常处理机制让你的程序变得更健壮。
    说明要包含2个部分:1. 问题说明(哪里会碰到异常)。2.解决方案(关键代码)

答:① 在登陆界面会出现异常,会出现账号密码不匹配的情况。
② 解决方案(关键代码)如下:

 >		String username = UsernameTextField.getText();
 		String password = PasswordTextField.getText();
 		try {
 			String realpassword = users.get(username);
 			if (password.equals(realpassword)) {
 				new Menu().setVisible(true);
 				ShoppingCart.this.dispose();
 			}
 		} catch (Exception e) {
 			new ErrorFlame().setVisible(true);       //弹出提示错误窗口
 		}

例:username应为“Guo”,password应为“123456”
若输入密码错误:

则出现提示:

3. 码云上代码提交记录及PTA实验总结

题目集:异常

3.1. 码云代码提交记录

原文地址:https://www.cnblogs.com/vicheng/p/6749204.html