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

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

   文件打不开、浏览界面出现乱码等,这些都是运行时错误。

   重启

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

   空指针异常和强制转换类型出错。这些错误是运行时错误。我认为编译错误更好解决,因为编译错误在代码写出后编译器就会直接报错,不给通过,还会提示错误原因;而运行时错误在运行时才会发生错误直接将程序卡退后才会提示错误。

3、查询JDK文档,说说如下代码哪行抛出了什么类型的异常?为什么该段程序明明可能产生错误,但是不写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();  
     x[i] = Integer.parseInt(inputInt);  //注意这里!
     i++;
 }
 System.out.println(Arrays.toString(x));
}

为上述代码添加try...catch。使得当输入错误时,可提示重新输入,直到输入正确后,才能继续往下执行。

当输入的数字不是int型时,会抛出数字类型异常NumberFormatException,但是此类异常属于免检异常,编译器不会报错,所以不用try catch 也可以运行。

添加try catch 之后:

public class Main {

    public static void main(String[] args) {

        int[] x = new int[3];

         Scanner inputScan = new Scanner(System.in);

         for(int i = 0; i < x.length;){

                 try {

                     System.out.println("Please input the "+i+" integer:");

                     String inputInt = inputScan.nextLine();  

                     x[i] = Integer.parseInt(inputInt);  

                     i++;

                } catch (Exception e) {

                    System.out.println("输入类型错误,请重新输入");

                    continue;//除非输入正确,否则一直输入

                }

            }

         System.out.println(Arrays.toString(x));

    }

}

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

String x = "abc";
try {
 int a = Integer.parseInt(x);
 System.out.println(a);
} catch (NumberFormatException e) {
 e.printStackTrace();
}

可以,因为NumberFormatException是Exception的子类,改成Exception后仍然抛出NumberFormatException的异常。

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

String fileName = "abc";
FileReader fileReader = new FileReader(fileName);

第二行会抛出FileNotFoundException异常

需要,因为他是受检异常,可以用try catch捕获,来实现正常运行。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值