需求
- 定義方法,出錯時拋出自定義異常。
try-catch 捕獲並處理。
- 定義方法調用並轉拋異常。
try-catch 捕獲並輸出異常拋出過程(堆棧追蹤)。
完整代碼示例
import java.util.ArrayList;
import java.util.List;
public class ExceptionTest {
// 1. 可能拋出自定義異常的方法
public static boolean isTargetInCertainIndex(String value, List<String> list, int index)
throws IllegalArgumentException, IndexOutOfBoundsException {
if (value == null || list == null) {
throw new IllegalArgumentException("data is null");
}
if (index >= list.size()) { // 注意:>=
throw new IndexOutOfBoundsException("index out of bounds");
}
return value.equals(list.get(index));
}
// 3. 調用並轉拋異常
public static void callerMethod(String value, List<String> list, int index) throws Exception {
try {
boolean flag = isTargetInCertainIndex(value, list, index);
System.out.println("flag: " + flag);
} catch (Exception e) {
System.out.println("callerMethod 捕獲並轉拋: " + e.getMessage());
throw e; // 轉拋
}
}
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("hello");
list.add("world");
list.add("I");
// 2. 直接捕獲處理
try {
boolean flag = isTargetInCertainIndex("hello", list, 0);
System.out.println("正常: " + flag);
} catch (Exception e) {
System.out.println("異常: " + e.getMessage());
}
// 4. 捕獲並輸出堆棧追蹤
try {
callerMethod(null, list, 0); // 觸發 IllegalArgumentException
} catch (Exception e) {
System.out.println("main 捕獲,完整堆棧:");
e.printStackTrace(); // 輸出拋出過程
}
}
}
關鍵點
- 自定義異常繼承
Exception(受檢)或 RuntimeException(非受檢)。
throw e 保留原始堆棧;throw new Exception(e) 會包裝為新異常。
e.printStackTrace() 輸出完整調用鏈,滿足「輸出拋出過程」需求。