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

javaobject oriented programmingprogramming

getCause() 方法来自 Throwable 类,我们可以使用此方法返回异常的 原因,如果异常的原因未知,则返回 nullgetCause() 方法不接受任何参数,也不会引发异常。它返回由其构造函数之一提供的原因,或由 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); // 抛出异常,由 main() 中的 catch 块捕获
         e.initCause(aiobe); // 将原因提供给 getCause()
      }
   }
}

输出

Cause = java.lang.ArrayIndexOutOfBoundsException: 8

相关文章