Java 编程中的已检查异常与未检查异常。
java 8object oriented programmingprogramming更新于 2025/11/7 7:40:17
已检查异常
已检查异常 是在编译时发生的异常,这些异常也称为编译时异常。这些异常在编译时不能被忽略;程序员应该注意(处理)这些异常。
当发生已检查/编译时异常时,您可以通过使用 try-catch 块处理它来恢复程序。使用这些,您可以显示自己的消息或在执行完整程序后显示异常消息。
示例
import java.io.File;
import java.io.FileInputStream;
public class Test {
public static void main(String args[]){
System.out.println("Hello");
try{
File file =new File("my_file");
FileInputStream fis = new FileInputStream(file);
}
catch(Exception e){
System.out.println("未找到给定的文件路径");
}
}
}
输出
Hello 未找到给定的文件路径
未检查异常
运行时异常或未检查异常是在执行时发生的异常。这些包括编程错误,例如逻辑错误或 API 的不当使用。运行时异常在编译时被忽略。
IndexOutOfBoundsException、ArithmeticException、ArrayStoreException 和 ClassCastException 是运行时异常的示例。
示例
在下面的 Java 程序中,我们有一个大小为 5 的数组,我们试图访问第 6 个元素,这会生成 ArrayIndexOutOfBoundsException。
public class ExceptionExample {
public static void main(String[] args) {
//创建一个大小为 5 的整数数组
int inpuArray[] = new int[5];
//填充数组
inpuArray[0] = 41;
inpuArray[1] = 98;
inpuArray[2] = 43;
inpuArray[3] = 26;
inpuArray[4] = 79;
//访问大于数组大小的索引
System.out.println( inpuArray[6]);
}
}
输出
运行时异常
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at July_set2.ExceptionExample.main(ExceptionExample.java:14)

