如何合理管控Java語言的異常
異常是程序運行過程中出現(xiàn)的錯誤。而異常的處理框架,是Java語言健壯性的一個重要體現(xiàn)。
1、介紹
Java把異常當(dāng)作對象來處理,并定義一個基類java.lang.Throwable作為所有異常的超類。
異常類分為兩大類,錯誤Error和異常Exception。Java異常體系結(jié)構(gòu)呈樹狀,其層次結(jié)構(gòu)圖如圖所示:
2、Thorwable類
Thorwable類所有異常和錯誤的超類,有兩個子類Error和Exception,分別表示錯誤和異常。
3、Error
系統(tǒng)錯誤(system error) 是由 Java 虛擬機拋出的,用 Error 類表示。
Error 類描述的是內(nèi)部系統(tǒng)錯誤,這樣的錯誤很少發(fā)生。如果發(fā)生,除了通知用戶以及盡量穩(wěn)妥地終止程序外,幾乎什么也不能做。
- OutOfMemoryError :內(nèi)存耗盡 ;
- NoClassDefFoundError :無法加載某個Class ;
- StackOverflowError :棧溢出。
4、Exception類
異常類Exception又分為運行時異常(RuntimeException)和非運行時異常,這兩種異常有很大的區(qū)別,也稱之為不檢查異常(Unchecked Exception)和檢查異常(Checked Exception)。
4.1、檢查異常
這類異常在編譯時就會被編譯器檢查,程序必須對其進行處理(捕獲或聲明拋出),否則無法通過編譯。常見的受檢查異常有:
IOException
:輸入輸出操作時可能出現(xiàn)的異常,如文件讀取失敗。SQLException
:執(zhí)行 SQL 語句時可能出現(xiàn)的異常。
4.2、運行時異常
這類異常在編譯時不會被編譯器檢查,程序可以選擇處理也可以不處理。常見的不受檢查異常有:
NullPointerException
:當(dāng)嘗試訪問一個空對象的方法或?qū)傩詴r拋出。ArrayIndexOutOfBoundsException
:當(dāng)訪問數(shù)組時使用的索引超出數(shù)組范圍時拋出。
5、處理方式
5.1. 捕獲異常
使用 try-catch
塊可以捕獲并處理異常。try
塊中包含可能會拋出異常的代碼,catch
塊用于捕獲并處理特定類型的異常。
public class TryCatchExample { public static void main(String[] args) { try { int[] numbers = {1, 2, 3}; // 這里會拋出 ArrayIndexOutOfBoundsException System.out.println(numbers[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("捕獲到數(shù)組越界異常: " + e.getMessage()); } } }
5.2. 多重捕獲
可以在一個 try
塊后面跟隨多個 catch
塊,用于捕獲不同類型的異常。
public class MultipleCatchExample { public static void main(String[] args) { try { int[] numbers = null; // 這里會拋出 NullPointerException System.out.println(numbers[0]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("捕獲到數(shù)組越界異常: " + e.getMessage()); } catch (NullPointerException e) { System.out.println("捕獲到空指針異常: " + e.getMessage()); } } }
5.3. thorws
如果一個方法可能會拋出受檢查異常,但不想在該方法內(nèi)部處理,可以使用 throws
關(guān)鍵字在方法聲明中聲明拋出該異常,將異常處理的責(zé)任交給調(diào)用者。
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ThrowsExample { public static void readFile() throws FileNotFoundException { File file = new File("nonexistent.txt"); Scanner scanner = new Scanner(file); } public static void main(String[] args) { try { readFile(); } catch (FileNotFoundException e) { System.out.println("捕獲到文件未找到異常: " + e.getMessage()); } } }
5.4. throw 關(guān)鍵字
可以使用 throw
關(guān)鍵字在代碼中手動拋出一個異常對象。
public class ThrowExample { public static void checkAge(int age) { if (age < 0) { throw new IllegalArgumentException("年齡不能為負數(shù)"); } System.out.println("年齡合法: " + age); } public static void main(String[] args) { try { checkAge(-5); } catch (IllegalArgumentException e) { System.out.println("捕獲到非法參數(shù)異常: " + e.getMessage()); } } }
5.5. finally 塊
finally
塊通常和 try-catch
塊一起使用,無論 try
塊中是否拋出異常,finally
塊中的代碼都會被執(zhí)行。
public class FinallyExample { public static void main(String[] args) { try { int[] numbers = {1, 2, 3}; // 這里會拋出 ArrayIndexOutOfBoundsException System.out.println(numbers[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("捕獲到數(shù)組越界異常: " + e.getMessage()); } finally { System.out.println("finally 塊中的代碼一定會執(zhí)行"); } } }
6、執(zhí)行順序
舉個簡單的例子,
1、在return的配合下,finally的return就是必須要執(zhí)行。
public static void main(String[] args) { int test = test(); System.out.println("test==="+test); } private static int test() { int x = 1; try { x= x/0; return 1; } catch (Exception e) { System.out.println("出現(xiàn)異常了:x="+x); return 2; } finally { return 3; } } 輸出: 出現(xiàn)異常了:x=1 test===3
2、finally如果沒有return,則判斷try代碼塊里面是否有異常,
- 如果有,則返回catch里面return;
- 如果沒有,則返回catch塊里面的return;
public static void main(String[] args) { int test = test(); System.out.println("test==="+test); } private static int test() { int x = 1; try { x= x/0; return 1; } catch (Exception e) { System.out.println("出現(xiàn)異常了:x="+x); return 2; } finally { // return 3; } } 輸出: 出現(xiàn)異常了:x=1 test===2
7、常見異常
1、java.lang.NullPointerException
空指針異常;出現(xiàn)原因:調(diào)用了未經(jīng)初始化的對象或者是不存在的對象。
public class NullArrayIterationExample { public static void main(String[] args) { int[] numbers = null; // 這里會拋出 NullPointerException,因為 numbers 為 null for (int num : numbers) { System.out.println(num); } } }
2、java.lang.ClassNotFoundException
指定的類找不到;出現(xiàn)原因:類的名稱和路徑加載錯誤;通常都是程序試圖通過字符串來加載某個類時可能引發(fā)異常。
public class ClassNotFoundForNameExample { public static void main(String[] args) { try { // 嘗試加載一個不存在的類 Class<?> clazz = Class.forName("com.example.NonExistentClass"); System.out.println("類加載成功:" + clazz.getName()); } catch (ClassNotFoundException e) { System.out.println("捕獲到 ClassNotFoundException: " + e.getMessage()); } } }
3、java.lang.NumberFormatException
字符串轉(zhuǎn)換為數(shù)字異常;出現(xiàn)原因:字符型數(shù)據(jù)中包含非數(shù)字型字符。
public class StringToIntExample { public static void main(String[] args) { String str = "abc"; try { // 嘗試將非數(shù)字字符串轉(zhuǎn)換為整數(shù) int num = Integer.parseInt(str); System.out.println("轉(zhuǎn)換后的整數(shù): " + num); } catch (NumberFormatException e) { System.out.println("捕獲到 NumberFormatException: " + e.getMessage()); } } }
4、java.lang.IndexOutOfBoundsException
數(shù)組角標越界異常,常見于操作數(shù)組對象時發(fā)生。
public class ArrayIndexOutOfBoundsExample { public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; try { // 嘗試訪問數(shù)組中不存在的索引位置 int element = array[10]; System.out.println("訪問到的元素是: " + element); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("捕獲到 ArrayIndexOutOfBoundsException: " + e.getMessage()); } } }
5、java.lang.IllegalArgumentException
方法傳遞參數(shù)錯誤。
public class CustomMethodExample { public static void calculateArea(int length, int width) { if (length <= 0 || width <= 0) { throw new IllegalArgumentException("長度和寬度必須為正數(shù)"); } int area = length * width; System.out.println("矩形的面積是: " + area); } public static void main(String[] args) { try { // 傳入不合法的參數(shù) calculateArea(-5, 10); } catch (IllegalArgumentException e) { System.out.println("捕獲到 IllegalArgumentException: " + e.getMessage()); } } }
6、java.lang.ClassCastException
當(dāng)試圖將對象強制轉(zhuǎn)換為它并不是的類型時會拋出該異常。
class Animal { public void eat() { System.out.println("Animal is eating."); } } class Dog extends Animal { public void bark() { System.out.println("Dog is barking."); } } class Cat extends Animal { public void meow() { System.out.println("Cat is meowing."); } } public class BasicClassCastExample { public static void main(String[] args) { Animal animal = new Cat(); try { // 嘗試將 Cat 對象強制轉(zhuǎn)換為 Dog 類型,會拋出異常 Dog dog = (Dog) animal; dog.bark(); } catch (ClassCastException e) { System.out.println("捕獲到 ClassCastException: " + e.getMessage()); } } }
7、文件已結(jié)束異常:EOFException
當(dāng)輸入過程中意外到達文件末尾(EOF)或者流結(jié)束時,就會拋出這個異常。通常在使用輸入流讀取數(shù)據(jù)時,如果嘗試讀取超出流末尾的數(shù)據(jù),就會觸發(fā)該異常。
import java.io.EOFException; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class EOFExceptionExample { public static void main(String[] args) { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.ser"))) { while (true) { // 嘗試從文件中讀取對象 Object obj = ois.readObject(); System.out.println(obj); } } catch (EOFException e) { // 當(dāng)?shù)竭_文件末尾時,捕獲 EOFException System.out.println("已到達文件末尾,讀取結(jié)束。"); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
8、文件未找到異常:FileNotFoundException
import java.io.FileInputStream; import java.io.FileNotFoundException; public class FileNotFoundExample1 { public static void main(String[] args) { try { // 嘗試打開一個不存在的文件 FileInputStream fis = new FileInputStream("nonexistentfile.txt"); } catch (FileNotFoundException e) { System.out.println("文件未找到: " + e.getMessage()); } } }
9、實例化異常:java.lang.InstantiationException
class AbstractClassExample { // 這是一個抽象類 public abstract static class MyAbstractClass { public abstract void doSomething(); } public static void main(String[] args) { try { // 嘗試實例化抽象類 MyAbstractClass obj = MyAbstractClass.class.newInstance(); } catch (InstantiationException e) { System.out.println("實例化異常: " + e.getMessage()); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
10、UnsupportedOperationException - 不支持的操作異常
import java.util.AbstractList; import java.util.List; public class ImmutableListExample { public static void main(String[] args) { List<String> immutableList = new AbstractList<String>() { @Override public String get(int index) { return "Element " + index; } @Override public int size() { return 10; } @Override public boolean add(String s) { throw new UnsupportedOperationException("此列表為不可變列表,不支持添加操作"); } }; try { immutableList.add("New Element"); } catch (UnsupportedOperationException e) { System.out.println(e.getMessage()); } } }
總結(jié)
通過掌握 Java 的異常處理機制,可以編寫出更健壯、可靠的程序,有效應(yīng)對各種異常情況。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java中處理金額計算之使用Long還是BigDecimal詳解
在Java后端開發(fā)中處理與錢有關(guān)的業(yè)務(wù)時,確保金額計算的準確性和避免錯誤非常重要,這篇文章主要給大家介紹了關(guān)于Java中處理金額計算之使用Long還是BigDecimal的相關(guān)資料,需要的朋友可以參考下2024-07-07Java操作redis實現(xiàn)增刪查改功能的方法示例
這篇文章主要介紹了Java操作redis實現(xiàn)增刪查改功能的方法,涉及java操作redis數(shù)據(jù)庫的連接、設(shè)置、增刪改查、釋放資源等相關(guān)操作技巧,需要的朋友可以參考下2017-08-08spring在service層的方法報錯事務(wù)不會回滾的解決
這篇文章主要介紹了spring在service層的方法報錯事務(wù)不會回滾的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02async-excel實現(xiàn)多sheet異步導(dǎo)出方法詳解
這篇文章主要介紹了async-excel實現(xiàn)多sheet異步導(dǎo)出方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-12-12SpringBoot整合RedisTemplate實現(xiàn)緩存信息監(jiān)控的基本操作
SpringBoot中的 redistemplate 是一個用于操作 Redis 數(shù)據(jù)庫的高級模板類,它提供了一組方法,可以方便地執(zhí)行常見的 Redis 操作,如存儲、檢索和刪除數(shù)據(jù),本文給大家介紹了SpringBoot整合RedisTemplate實現(xiàn)緩存信息監(jiān)控的基本操作,需要的朋友可以參考下2025-02-02SpringBoot整合jasypt實現(xiàn)數(shù)據(jù)加密的步驟
聽說過jasypt嗎?它可是一個超級流行的Java庫哦,提供了簡單又高效的加密和解密接口,整合jasypt后,我們的SpringBoot應(yīng)用就能輕松處理敏感數(shù)據(jù)的加密和解密,而不必為復(fù)雜的加密算法頭疼啦,下面給大家介紹SpringBoot整合jasypt實現(xiàn)數(shù)據(jù)加密的步驟,感興趣的朋友一起看看吧2025-04-04如何利用java中String類的substring()字符串截取最后一個字符
Java中的String是不可變的類型,因此substring()方法并不會改變原字符串,而是返回了一個新的字符串,這篇文章主要介紹了如何利用java中String類的substring()字符串截取最后一個字符,需要的朋友可以參考下2023-11-11