首頁  >  文章  >  Java  >  深入研究 Java 異常

深入研究 Java 異常

PHPz
PHPz原創
2024-08-19 06:01:02459瀏覽

Java核心異常類

異常類別的層次結構: Throwable

可投擲

Throwable 類別是 Java 語言中所有錯誤和異常的超類別。只有屬於該類別(或其子類別之一)實例的物件才會被 Java 虛擬機器拋出或可以被 Java throw 語句拋出。參考

實際上,開發人員通常不會直接使用 Throwable。相反,它作為其兩個直接子類別的基礎:Error 和 Exception。

try {
 // some process
} catch (Throwable t) {
    throw new Throwable(t);
}

錯誤

Error 是 Throwable 的子類,它指示合理的應用程式不應嘗試捕獲的嚴重問題。錯誤通常代表 JVM 本身發生的異常情況參考

異常情況意味著問題通常是由應用程式無法控制的因素引起的,並且通常無法恢復。例如:OutOfMemoryError、StackOverflowError

Deep Dive into Java Exceptions

例外

異常是指程式執行過程中發生的意外事件或情況,我們應該嘗試catch。透過捕獲異常,我們應該能夠優雅地處理意外情況,確保程式不會崩潰。

int[] arr = {1, 2, 3};
try {
    System.out.println(arr[3]); // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Unchecked Exception: " + e.getMessage());
}

 

例外的類型

java有兩種類型的異常。參考

檢查異常

檢查異常就像您知道可能會出錯的情況,因此您需要為此做好計劃。它們必須使用 try-catch 區塊捕獲,或使用 throws 子句在方法簽名中聲明。如果一個方法可以拋出一個已檢查的異常並且您不處理它,則程式將無法編譯。

// Checked exception
try {
    readFile("nonexistent.txt");
} catch (FileNotFoundException e) {
    System.out.println("Checked Exception: " + e.getMessage());
}
// Checked exception
public void getData() throws SQLException { // throw SQLException
    throw new SQLException("err");
}

未經檢查的異常

未檢查的異常,又稱。運行時異常是 Java 編譯器不需要您處理的異常。它們是 RuntimeException 的子類別。與檢查異常不同,這些異常不需要在方法簽名中捕獲或聲明。它們通常表示程式設計錯誤,例如邏輯缺陷、API 使用不正確或違反程式碼中的假設。

String text = null;
System.out.println(text.length()); // This will throw a NullPointerException

 

Java異常的常見類型

NullPointerException:當應用程式嘗試使用尚未初始化的物件參考時發生。

String text = null; // text is not initialized
try {
    System.out.println(text.length()); // Attempting to call length() on a null reference
} catch (NullPointerException e) {
    System.out.println("Caught a NullPointerException: " + e.getMessage());
}

ArrayIndexOutOfBoundsException:當嘗試存取具有非法索引的陣列時拋出。

int[] numbers = {1, 2, 3};
try {
    int value = numbers[5]; // Attempting to access index 5, which is out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Caught an ArrayIndexOutOfBoundsException: " + e.getMessage());
}

IllegalArgumentException:當方法接收到不適當的參數時拋出。

public class IllegalArgumentExample {
    public static void setAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative"); // Illegal argument
        }
        System.out.println("Age set to: " + age);
    }

    public static void main(String[] args) {
        try {
            setAge(-5); // Passing a negative age, which is illegal
        } catch (IllegalArgumentException e) {
            System.out.println("Caught an IllegalArgumentException: " + e.getMessage());
        }
    }
}

 

如何處理異常

試著捕捉

當您想要處理程式碼區塊中可能拋出的特定異常時,請使用 try-catch

try {
    int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Caught an ArithmeticException: " + e.getMessage());
}

多重捕獲

當你想以類似的方式處理多種異常類型時,請使用多重捕獲

try {
    String str = null;
    System.out.println(str.length()); // This will throw NullPointerException
} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
    System.out.println("Caught an exception: " + e.getMessage());
}

嘗試資源

當您處理使用後需要關閉的資源(例如檔案、套接字或資料庫連線)時,請使用 try-with-resources。

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    System.out.println("Caught an IOException: " + e.getMessage());
}

最後

當您需要確保無論是否拋出異常都執行某些程式碼時,請使用finally區塊

try {
    file = new FileReader("file.txt");
} catch (IOException e) {
    System.out.println("Caught an IOException: " + e.getMessage());
} finally {
    if (file != null) {
        file.close(); // Ensure the file is closed
    }
}

 

異常處理的最佳實踐

不要忽略異常:異常應該得到適當的處理,而不僅僅是捕獲和忽略。

try {
    file = new FileReader("file.txt");
} catch (IOException ignored) {
    // ignored
}

使用特定異常:使用特定異常而不是通用異常。

try {
    // Code that may throw exceptions
    String text = null;
    text.length();
} catch (Exception e) {
    // Too broad; will catch all exceptions
    System.err.println("An error occurred: " + e.getMessage());
}

正確處理方法:

try {
    // Code that may throw exceptions
    String text = null;
    text.length();
} catch (NullPointerException e) {
    // Handle specific exception
    System.err.println("Null pointer exception: " + e.getMessage());
} catch (Exception e) {
    // Handle other exceptions
    System.err.println("An error occurred: " + e.getMessage());
}

清潔資源處理:始終關閉資源以避免記憶體洩漏

FileReader fileReader = null;
try {
    fileReader = new FileReader("file.txt");
    // Read from the file
} catch (IOException e) {
    System.err.println("File not found: " + e.getMessage());
} finally {
   fileReader.close(); // clouse resources
}

自訂異常:當標準異常不適合特定錯誤條件時建立自訂異常。

// Custom Exception
public class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

// Usage
public class Example {
    public void performOperation() throws CustomException {
        // Some condition
        throw new CustomException("Custom error message");
    }

    public static void main(String[] args) {
        Example example = new Example();
        try {
            example.performOperation();
        } catch (CustomException e) {
            System.err.println("Caught custom exception: " + e.getMessage());
        }
    }
}

日誌記錄:記錄異常以進行偵錯和維護。

public class Example {
    private static final Logger logger = Logger.getLogger(Example.class.getName());

    public void riskyMethod() {
        try {
            // Code that may throw an exception
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            // Log the exception
            logger.severe("An arithmetic error occurred: " + e.getMessage());
        }
    }
}

避免過度使用異常:警告不要使用異常來控制流程;它們應該只用於處理真正的特殊情況。

public class Example {
    public void process(int[] array) {
        try {
            // Using exceptions to control flow
            if (array.length < 5) {
                throw new ArrayIndexOutOfBoundsException("Array too small");
            }
            // Process array
        } catch (ArrayIndexOutOfBoundsException e) {
            // Handle exception
            System.out.println("Handled array size issue.");
        }
    }
}

正確處理方法:

public class Example {
    public void process(int[] array) {
        if (array.length >= 5) {
            // Process array
        } else {
            // Handle the condition without using exceptions
            System.out.println("Array is too small.");
        }
    }
}

 
任何回饋都會有幫助:)

以上是深入研究 Java 異常的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn