第10周 预习、实验与作业:异常处理机制

课前问题列表

1. 说出两个我们在使用软件、APP时遇到的错误。这些错误可能是什么类型的错误?你是怎么解决这类错误呢(重启、查看日志…)?

  1. 遇到问题:软件或App在使用的时候突然崩溃。
    解决方法:这种情况下一般就是重启了
  2. 遇到问题:软件或App报错
    解决方法:上网搜索相关的解决方法。

2. 说出两个你在编写Java程序时最常遇到的错误。并判定这些错误是什么类型的错误(编译错误、运行时错误)。你认为哪种类型的错误更好解决呢?

编译错误更好解决,可以通过提示对代码进行有效的修改。

3. 查询JDK文档,说说如下代码哪行抛出了什么类型的异常?为什么该段程序明明可能产生错误,但是不写try…catch,也可编译通过。

1.	public static void main(String[] args) {
2.	 int[] x = new int[3];
3.	 Scanner inputScan = new Scanner(System.in);
4.	 for(int i = 0; i < x.length;){
5.	     System.out.println("Please input the "+i+" integer:");
6.	     String inputInt = inputScan.nextLine();  
7.	     x[i] = Integer.parseInt(inputInt);  //注意这里!
8.	     i++;
9.	 }
10.	 System.out.println(Arrays.toString(x));
11.	}

1)第七行抛出了:NumberFormatException(在输入非int型的情况下)
2)原因可能是:NumberFormatException属于免检异常,可以不对其进行捕获,故可以不使用try…catch。
3)为上述代码添加try…catch。使得当输入错误时,可提示重新输入,直到输入正确后,才能继续往下执行。添加后,如下所示:

public static void main(String[] args) {
		int[] x = new int[3];
		Scanner inputScan = new Scanner(System.in);
		for (int i = 0; i < x.length;) {
			System.out.println("Please input the " + i + " integer:");
			String inputInt = inputScan.nextLine();
			try {
			x[i] = Integer.parseInt(inputInt); // 注意这里!
			}catch(NumberFormatException e) {
				System.out.println("NumberFormatException!请重新输入:");
				continue;
			}
			i++;
		}
		System.out.println(Arrays.toString(x));
}

测试结果如下:
在这里插入图片描述

4. 将如下代码中NumberFormatException改成Exception可以吗?

1.	String x = "abc";
2.	try {
3.	 int a = Integer.parseInt(x);
4.	 System.out.println(a);
5.	} catch (NumberFormatException e) {
6.	 e.printStackTrace();
7.	}

使用NumberFormatException:
在这里插入图片描述
使用Exception:
在这里插入图片描述
如上所示,我们不难看出可以将NumberFormatException改成Exception。

5. 查询JDK文档,说说如下代码哪里抛出了什么异常?该异常意味着吗什么?需要捕获吗?为什么?

1.	String fileName = "abc";
2.	FileReader fileReader = new FileReader(fileName);

1)第二行抛出FileNotFoundException异常,该异常意味着找不到所要调用文件。
2)需要捕获异常,FileNotFoundException属于受检异常,可以使用try…catch处理。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值