首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 自定義異常、捕獲、轉拋與堆棧追蹤完整示例

     編輯:程式設計綜合問答

需求

  1. 定義方法,出錯時拋出自定義異常。
  2. try-catch 捕獲並處理。
  3. 定義方法調用並轉拋異常。
  4. 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() 輸出完整調用鏈,滿足「輸出拋出過程」需求。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved