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()
      }
   }
}

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

输出

Cause = java.lang.ArrayIndexOutOfBoundsException: 8

更新时间:2020-07-03

2K+ 浏览

开启你的 职业 生涯

完成课程,获得认证

立即开始
广告