Java 中 getCause() 方法的重要性?\n


getCause() 方法來自 Throwable 類,我們可以使用該方法,它返回異常的 cause 或在異常的 cause 不知道時返回 nullgetCause() 方法不接受任何引數,也不丟擲異常。它返回由其一個建構函式提供的或由 ThrowableinitCause() 方法的形成確定的 cause。

語法

public Throwable getCause()

示例

public class GetCauseMethodTest {
   public static void main(String[] args) throws Exception {
      try {
         myException();
      } catch(Exception e) {
         System.out.println("Cause = " + e.getCause());
      }
   }
   public static void myException() throws Exception {
      int arr[] = {1, 3, 5};
      try {
         System.out.println(arr[8]);
      } catch(ArrayIndexOutOfBoundsException aiobe) {
         Exception e = new Exception();
         throw(Exception); // throwing the exception to be caught by catch block in main()
         e.initCause(aiobe); // supplies the cause to getCause()
      }
   }
}

輸出

Cause = java.lang.ArrayIndexOutOfBoundsException: 8

更新時間:2020-07-03

2K+ 瀏覽

開啟你的 職業 生涯

完成課程,獲得認證

立即開始
廣告
© . All rights reserved.