如何合理管控Java語言的異常
異常是程序運(yùn)行過程中出現(xiàn)的錯(cuò)誤。而異常的處理框架,是Java語言健壯性的一個(gè)重要體現(xiàn)。
1、介紹
Java把異常當(dāng)作對(duì)象來處理,并定義一個(gè)基類java.lang.Throwable作為所有異常的超類。
異常類分為兩大類,錯(cuò)誤Error和異常Exception。Java異常體系結(jié)構(gòu)呈樹狀,其層次結(jié)構(gòu)圖如圖所示:

2、Thorwable類
Thorwable類所有異常和錯(cuò)誤的超類,有兩個(gè)子類Error和Exception,分別表示錯(cuò)誤和異常。
3、Error
系統(tǒng)錯(cuò)誤(system error) 是由 Java 虛擬機(jī)拋出的,用 Error 類表示。
Error 類描述的是內(nèi)部系統(tǒng)錯(cuò)誤,這樣的錯(cuò)誤很少發(fā)生。如果發(fā)生,除了通知用戶以及盡量穩(wěn)妥地終止程序外,幾乎什么也不能做。

- OutOfMemoryError :內(nèi)存耗盡 ;
- NoClassDefFoundError :無法加載某個(gè)Class ;
- StackOverflowError :棧溢出。
4、Exception類
異常類Exception又分為運(yùn)行時(shí)異常(RuntimeException)和非運(yùn)行時(shí)異常,這兩種異常有很大的區(qū)別,也稱之為不檢查異常(Unchecked Exception)和檢查異常(Checked Exception)。
4.1、檢查異常
這類異常在編譯時(shí)就會(huì)被編譯器檢查,程序必須對(duì)其進(jìn)行處理(捕獲或聲明拋出),否則無法通過編譯。常見的受檢查異常有:
IOException:輸入輸出操作時(shí)可能出現(xiàn)的異常,如文件讀取失敗。SQLException:執(zhí)行 SQL 語句時(shí)可能出現(xiàn)的異常。
4.2、運(yùn)行時(shí)異常
這類異常在編譯時(shí)不會(huì)被編譯器檢查,程序可以選擇處理也可以不處理。常見的不受檢查異常有:
NullPointerException:當(dāng)嘗試訪問一個(gè)空對(duì)象的方法或?qū)傩詴r(shí)拋出。ArrayIndexOutOfBoundsException:當(dāng)訪問數(shù)組時(shí)使用的索引超出數(shù)組范圍時(shí)拋出。
5、處理方式
5.1. 捕獲異常
使用 try-catch 塊可以捕獲并處理異常。try 塊中包含可能會(huì)拋出異常的代碼,catch 塊用于捕獲并處理特定類型的異常。
public class TryCatchExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
// 這里會(huì)拋出 ArrayIndexOutOfBoundsException
System.out.println(numbers[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("捕獲到數(shù)組越界異常: " + e.getMessage());
}
}
}5.2. 多重捕獲
可以在一個(gè) try 塊后面跟隨多個(gè) catch 塊,用于捕獲不同類型的異常。
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] numbers = null;
// 這里會(huì)拋出 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
如果一個(gè)方法可能會(huì)拋出受檢查異常,但不想在該方法內(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)鍵字在代碼中手動(dòng)拋出一個(gè)異常對(duì)象。
public class ThrowExample {
public static void checkAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("年齡不能為負(fù)數(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 塊中的代碼都會(huì)被執(zhí)行。
public class FinallyExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
// 這里會(huì)拋出 ArrayIndexOutOfBoundsException
System.out.println(numbers[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("捕獲到數(shù)組越界異常: " + e.getMessage());
} finally {
System.out.println("finally 塊中的代碼一定會(huì)執(zhí)行");
}
}
}6、執(zhí)行順序
舉個(gè)簡單的例子,
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===32、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===27、常見異常
1、java.lang.NullPointerException
空指針異常;出現(xiàn)原因:調(diào)用了未經(jīng)初始化的對(duì)象或者是不存在的對(duì)象。
public class NullArrayIterationExample {
public static void main(String[] args) {
int[] numbers = null;
// 這里會(huì)拋出 NullPointerException,因?yàn)?numbers 為 null
for (int num : numbers) {
System.out.println(num);
}
}
}2、java.lang.ClassNotFoundException
指定的類找不到;出現(xiàn)原因:類的名稱和路徑加載錯(cuò)誤;通常都是程序試圖通過字符串來加載某個(gè)類時(shí)可能引發(fā)異常。
public class ClassNotFoundForNameExample {
public static void main(String[] args) {
try {
// 嘗試加載一個(gè)不存在的類
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ù)組角標(biāo)越界異常,常見于操作數(shù)組對(duì)象時(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ù)錯(cuò)誤。
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)試圖將對(duì)象強(qiáng)制轉(zhuǎn)換為它并不是的類型時(shí)會(huì)拋出該異常。
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 對(duì)象強(qiáng)制轉(zhuǎn)換為 Dog 類型,會(huì)拋出異常
Dog dog = (Dog) animal;
dog.bark();
} catch (ClassCastException e) {
System.out.println("捕獲到 ClassCastException: " + e.getMessage());
}
}
}7、文件已結(jié)束異常:EOFException
當(dāng)輸入過程中意外到達(dá)文件末尾(EOF)或者流結(jié)束時(shí),就會(huì)拋出這個(gè)異常。通常在使用輸入流讀取數(shù)據(jù)時(shí),如果嘗試讀取超出流末尾的數(shù)據(jù),就會(huì)觸發(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) {
// 嘗試從文件中讀取對(duì)象
Object obj = ois.readObject();
System.out.println(obj);
}
} catch (EOFException e) {
// 當(dāng)?shù)竭_(dá)文件末尾時(shí),捕獲 EOFException
System.out.println("已到達(dá)文件末尾,讀取結(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 {
// 嘗試打開一個(gè)不存在的文件
FileInputStream fis = new FileInputStream("nonexistentfile.txt");
} catch (FileNotFoundException e) {
System.out.println("文件未找到: " + e.getMessage());
}
}
}9、實(shí)例化異常:java.lang.InstantiationException
class AbstractClassExample {
// 這是一個(gè)抽象類
public abstract static class MyAbstractClass {
public abstract void doSomething();
}
public static void main(String[] args) {
try {
// 嘗試實(shí)例化抽象類
MyAbstractClass obj = MyAbstractClass.class.newInstance();
} catch (InstantiationException e) {
System.out.println("實(shí)例化異常: " + 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 的異常處理機(jī)制,可以編寫出更健壯、可靠的程序,有效應(yīng)對(duì)各種異常情況。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
spring?項(xiàng)目實(shí)現(xiàn)限流方法示例
這篇文章主要為大家介紹了spring項(xiàng)目實(shí)現(xiàn)限流的方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
Spring?Boot中的max-http-header-size配置方式
這篇文章主要介紹了Spring?Boot中的max-http-header-size配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
SpringBoot讀取yml文件中配置數(shù)組的2種方法
這篇文章主要介紹了SpringBoot讀取yml文件中配置數(shù)組的2種方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
java實(shí)現(xiàn)字符串反轉(zhuǎn)案例
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)字符串反轉(zhuǎn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-09-09
Java手把手必會(huì)的實(shí)例漢諾塔講解練習(xí)
漢諾塔,傳說神在創(chuàng)造世界的時(shí)候做了三根金剛石柱子,并在一個(gè)教塔里留下了三根金剛石棒,第一根上面從上到下套著64個(gè)按從小到大排列的金盤,神命令廟里的眾僧將它們一個(gè)個(gè)地從這根金剛石棒搬到另一根金剛石棒上,大盤不能放在小盤上。最后64個(gè)金盤仍然要按從小到大排列2021-09-09
配置springboot項(xiàng)目使用外部tomcat過程解析
這篇文章主要介紹了配置springboot項(xiàng)目使用外部tomcat過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
Java 如何將網(wǎng)絡(luò)資源url轉(zhuǎn)化為File文件
這篇文章主要介紹了Java 如何將網(wǎng)絡(luò)資源url轉(zhuǎn)化為File文件的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
springmvc中進(jìn)行數(shù)據(jù)保存以及日期參數(shù)的保存過程解析
這篇文章主要介紹了springmvc中進(jìn)行數(shù)據(jù)保存以及日期參數(shù)的保存過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
詳解SpringBoot項(xiàng)目整合Vue做一個(gè)完整的用戶注冊(cè)功能
本文主要介紹了SpringBoot項(xiàng)目整合Vue做一個(gè)完整的用戶注冊(cè)功能,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
SpringBoot @PropertySource與@ImportResource有什么區(qū)別
這篇文章主要介紹了SpringBoot @PropertySource與@ImportResource有什么區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-01-01

