處理未檢查異常的 Java 程式


在本文中,我們將學習如何在 Java 中處理未檢查異常。

異常 是在程式實現過程中(即執行時)發生的意外情況,這些情況會中斷程式的正常執行。

它可能由多種原因引起,例如使用者提供的非法輸入、裝置故障、網路連線丟失、物理限制、程式碼錯誤、嘗試開啟不可用的檔案等。

異常主要分為兩大類  

  • 已檢查異常

  • 未檢查異常

在這裡,我們將處理未檢查異常。

未檢查異常進一步包括以下內容:

  • Error 類異常 - OutOfMemoryError 異常、StackOverflow 異常等

  • 執行時異常類 - NullPointerException、IndexOutOfBoundsException 等。

我們將學習如何處理這裡面兩種最常見的異常型別。這些異常是NullPointerExceptionIndexOutOfBoundsException

IndexOutOfBoundsException

當程式設計師試圖檢索索引大於或等於陣列長度(因為陣列的索引從 0 開始)的元素時,就會出現此異常。由於遇到此異常,程式會自動終止。

示例 1

import java.io.*;
public class ExceptionExample1 {
   public static void main(String[] args){
      //creation of an array of length 6 
      int arr[] = { 40, 32, 33, 14, 56, 90 };
      // Trying to retrieve an element greater than
      // index size of the array
      System.out.println(arr[10]);
   }
}

輸出

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 6
	at ExceptionExample1.main(ExceptionExample1.java:8)

示例 2

當用戶嘗試檢索等於陣列索引大小的陣列元素時。

import java.io.*;
public class ExceptionExample1 {
   public static void main(String[] args){
      //creation of an array of length 6
      int arr[] = { 40, 32, 33, 14, 56, 90 };
      // Trying to retrieve an element equal to the
      // index size of the array
      System.out.println(arr[6]);
   }
}

輸出

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
	at ExceptionExample1.main(ExceptionExample1.java:8)

處理 ArrayIndexOutOfBoundsException

此異常可以透過try-catch語句處理。

try 語句使程式設計師能夠定義一段程式碼塊以測試是否存在可能的錯誤,而 catch 塊捕獲給定的異常物件並執行所需的運算。因此,程式將成功執行,而不會像上述情況那樣意外停止。

示例

import java.io.*;
public class ExceptionExample1 {
   public static void main(String[] args) {
      
      // Filling the array with 6 array elements
      int arr[] = { 40, 32, 33, 14, 56, 90 };
      
      // Try block for exceptions
      try {
         
         // trying to retrieve and print the
         
         // element that is out of the scope of indexes of this array
         System.out.println(arr[10]);
      }
      
      // Catch block to catch the exceptions
      catch (ArrayIndexOutOfBoundsException e) {
         
         // displaying message when index which is not
         
         // present in an array is being accessed
         System.out.println(
         "Array Out of index please rectify your code");
      }
   }
}

輸出

Array Out of index please rectify your code

NullPointerException

當試圖檢索具有空值的 object 引用時,會遇到此異常。

示例

import java.io.*;
public class ExceptionExample2 {
   public static void main(String[] args) {
      // Instance of string str has a null value
      String str = null;
      // Comparison of the null value with the other string
      // throws an exception and prints the same
      System.out.println(str.equals("Hello"));
   }
}

輸出

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "" is null
	at ExceptionExample2.main(ExceptionExample2.java:8)

處理 NullPointerException

此異常也可以透過try-catch語句處理。

示例

import java.io.*;
public class ExceptionExample2 {
   public static void main(String[] args) {
      // Assigning NULL value to a string
      String str = null;
      try {
         // Trying to compare the null value with another string
         // and throw an exception
         if (str.equals("Hello")) {
            // print the following string if it is true
            System.out.println("TRUE");
         }
      }
      catch (NullPointerException e) {
         // dealing with the exception
         System.out.println("Object Reference can't be null");
      }
   }
}

輸出

Object Reference can't be null

在本教程中,我們討論了處理未檢查異常的 Java 程式 - NullPointerException 和 IndexOutOfBoundsException。

更新於: 2024 年 9 月 24 日

939 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告