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

的getCause()方法是从Throwable的 类,我们可以用这种方法它返回原因 的异常的返回 零 ,如果异常的原因是未知的。该的getCause()方法不接受任何参数,并且不抛出异常。它返回由其构造函数之一提供的原因,或者由Throwable 类的initCause() 方法形成的原因。

语法

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