Java编程中Checked与Unchecked异常。

检查异常

检查的异常 是在编译时发生的异常,这些也称为编译时异常。这些异常不能在编译时简单地忽略。程序员应注意(处理)这些异常。

当发生检查/编译时异常时,您可以使用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) {
      //创建一个大小为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)