携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第31天,点击查看活动详情
编译异常
编译异常就是在编译期间就要处理的异常,也叫受查异常,就是说编译器在编译期间会进行检查,不处理该异常,就无法通过编译。
编译异常必须处理!
常见编译异常:
1.SQLException //操作数据库时,查询表可能发生异常
2.IOException //操作文件时,发生的异常
3.FileNotFoundException //当操作一个不存在文件时,发生的异常
4.EOFException//操作文件,文件到末尾,发生的异常
5.IllegalArgumentException//参数异常
编译异常举例
因为bug郭还没有学习到数据库和文件操作。我们就举一个案例来了解一下编译异常!
//操作文件,发生的编译异常
public class IOException_ {
public static void main(String[] args) {
File file = new File("D:\\a.txt");
file.createNewFile();//异常
}
}
可以看到编译异常,如果我们不进行处理,代码就无法编译通过!
//try-catch处理异常
public static void main(String[] args) {
File file = new File("D:\\a.txt");
//try-catch处理异常 快捷键:Ctrl+Alt+T
try {
file.createNewFile();//异常
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
异常课堂练习
我们了解了异常,哪来看看下面代码是否会发生异常吧!
//题目一
public static void main(String[] args) {
String[] strings = new String[]{"java","bug","2022"};
System.out.println(strings[3]);
}
结果:
ArrayIndexOutOfBoundsException数组下标越界异常
//题目二
public static void main(String[] args) {
String string = "java";
Object ob = string;
Integer integer = (Integer)ob;
}
ClassCastException类型转换异常
//题目三
class Cat{
public String name;
Cat(String name){
this.name = name;
}
}
public class test_1 {
public static void main(String[] args) {
Cat cat= new Cat("豆花");
cat = null;
System.out.println(cat.name);
}
}
-NullPointerException空指针异常
//题目四
public class Test_1 {
public static void main(String[] args) {
int[] array = new int[]{1,3,3,4,5,6};
array = null;
for (int x:
array) {
System.out.print(x+" ");
}
}
}