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)

更新於: 2019-09-06

778 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.