Java 中的已检查异常与未检查异常\
java programming java8object oriented programming
已检查异常
已检查异常是在编译时发生的异常,也称为编译时异常。这些异常在编译时不能被忽略,程序员应该注意(处理)这些异常。
例如,如果您在程序中使用 FileReader 类从文件读取数据,如果其构造函数中指定的文件不存在,则会发生 FileNotFoundException,编译器会提示程序员处理异常。
示例
import java.io.File; import java.io.FileReader; public class FilenotFound_Demo { public static void main(String args[]) { File file = new File("E://file.txt"); FileReader fr = new FileReader(file); } }
如果您尝试编译上述程序,您将得到以下异常。
输出
C:\>javac FilenotFound_Demo.java FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown FileReader fr = new FileReader(file); ^ 1 error
注意− 由于 FileReader 类的 read() 和 close() 方法会抛出 IOException,因此您可以观察到编译器会通知处理 IOException 以及 FileNotFoundException。
未检查异常
未检查异常是在执行时发生的异常。这些也被称为运行时异常。这些包括编程错误,例如逻辑错误或 API 的不当使用。运行时异常在编译时被忽略。
例如,如果您在程序中声明了一个大小为 5 的数组,并尝试调用该数组的第 6 个元素,则会发生 ArrayIndexOutOfBoundsExceptionexception。
示例
public class Unchecked_Demo { public static void main(String args[]) { int num[] = {1, 2, 3, 4}; System.out.println(num[5]); } }
如果您编译并执行上述程序,您将得到以下异常。
输出
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)