正所谓写代码五分钟,修bug两小时,在日常开发过程中,没有一个程序员是能够百分百开发出一个没有 bug 的程序的,因此,为了更好的排除 bug 和处理资源回收的问题,异常 在这过程中就起到了关键性的作用。
在 Java 中,异常被分为了受查异常 (checked exception)和 非受查异常(unchecked exception)两种,非受查异常又叫运行时异常,即 RuntimeException,除了 RuntimeException 的异常都是受查异常,即 Exception。
受查异常
受查异常 在程序编译中是严格要求程序员捕获或抛出的异常,没有处理的异常编译器会自动标红,提示程序员进行捕获或抛出,否则编译就不能通过。比如我写个读取文件的程序:
运行结果:
因为我们并没有捕获或抛出异常,所以编译器标红,且编译不通过。捕获异常使用 try...catch,抛出异常使用 throws。
try...catch 捕获异常
import java.io.*;
public class Demo {
public static void main(String[] args){
try {
//访问 hhh.txt 文件
InputStream inputStream = new FileInputStream(new File("G:\\111\\hhh.txt"));
int i = 0;
//一次读取一个字节
while ((i = inputStream.read()) != -1) {
//输出文件内容
System.out.print((char) i);
}
//关闭io流
inputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
throws 抛出异常
import java.io.*;
public class Demo {
public static void main(String[] args){
try {
//访问 hhh.txt 文件
InputStream inputStream = new FileInputStream(new File("G:\\111\\hhh.txt"));
int i = 0;
//一次读取一个字节
while ((i = inputStream.read()) != -1) {
//输出文件内容
System.out.print((char) i);
}
//关闭io流
inputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
运行结果:
常见的受查异常因为遇到时编译器会自动标红,这里就不举例了。
非受查异常
非受查异常(运行时异常)顾名思义就是在运行中出现的异常,编译器不要求程序员一定要捕获或抛出,遇到该异常时,程序会被自动终止,并在控制台爆红,显示出现的异常,比如:
public class Demo {
public static void main(String[] args){
Integer i = null;
int j = i * 5;
System.out.println(j);
}
}
执行结果:
像这种空指针异常(NullPointerException)就属于运行时异常,常见的运行时异常有:空指针异常(NullPointerException),类转换异常(ClassCastException),下标越界异常(IndexOutOfBoundsException),数字格式异常(NumberFormatException),计算异常(ArithmeticException),非法参数异常(IllegalArgumentException),数据存储异常(ArrayStoreException),IO 操作的缓冲区上溢异常(BufferOverflowException)等等。