Java 编程中的已检查异常和未检查异常。
已检查异常
已检查异常是在编译时发生的异常,也称为编译时异常。在编译时不能简单地忽略这些异常;程序员应该注意(处理)这些异常。
当发生已检查/编译时异常时,您可以使用 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("Given file path is not found");
}
}
}输出
Hello Given file path is not found
未检查异常
运行时异常或未检查异常是在执行时发生的异常。这些包括编程错误,例如逻辑错误或 API 的不正确使用。运行时异常在编译时被忽略。
IndexOutOfBoundsException、ArithmeticException、ArrayStoreException 和 ClassCastException 是运行时异常的示例。
示例
在下面的 Java 程序中,我们有一个大小为 5 的数组,我们试图访问第 6 个元素,这会生成ArrayIndexOutOfBoundsException。
public class ExceptionExample {
public static void main(String[] args) {
//Creating an integer array with size 5
int inpuArray[] = new int[5];
//Populating the array
inpuArray[0] = 41;
inpuArray[1] = 98;
inpuArray[2] = 43;
inpuArray[3] = 26;
inpuArray[4] = 79;
//Accessing index greater than the size of the array
System.out.println( inpuArray[6]);
}
}输出
运行时异常
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at July_set2.ExceptionExample.main(ExceptionExample.java:14)
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP