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捕获,来实现正常运行。