Java Throwable getCause() 方法



描述

Java Throwable getCause() 方法返回此可丟擲物件的根本原因,如果原因不存在或未知,則返回 null。

宣告

以下是 java.lang.Throwable.getCause() 方法的宣告:

public Throwable getCause()

引數

返回值

此方法返回此可丟擲物件的根本原因,如果原因不存在或未知,則返回 null。

異常

示例:獲取 Throwable 的初始原因

以下示例演示了 java.lang.Throwable.getCause() 方法的使用。在此程式中,我們定義了一個名為 raiseException() 的方法,在其中定義了一個 Throwable,並使用 initCause() 方法將其初始原因設定為帶有訊息“ABCD”的可丟擲物件。在 main 方法中,呼叫了 raiseException() 方法。在 catch 塊中,我們處理異常並使用 getCause() 方法列印其原因。

package com.tutorialspoint;

public class ThrowableDemo {

   public static void main(String[] args) throws Throwable {
     try {
         raiseException();
      } catch(Throwable e) {
         System.out.println(e.getCause());
      }
   }
  
   public static void raiseException() throws Throwable {

      Throwable t = new Throwable("This is new Exception...");
      t.initCause(new Throwable("ABCD"));
      throw t;
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

java.lang.Throwable: ABCD

示例:獲取 RuntimeException 的初始原因

以下示例演示了 java.lang.Throwable.getCause() 方法的使用。在此程式中,我們定義了一個名為 raiseException() 的方法,在其中定義了一個 RuntimeException,並使用 initCause() 方法將其初始原因設定為帶有訊息“ABCD”的可丟擲物件。在 main 方法中,呼叫了 raiseException() 方法。在 catch 塊中,我們處理異常並使用 getCause() 方法列印其原因。

package com.tutorialspoint;

public class ThrowableDemo {

   public static void main(String[] args) throws Throwable {
     try {
         raiseException();
      } catch(Exception e) {
        System.out.println(e.getCause());
      }
   }
  
   public static void raiseException() throws RuntimeException {

      RuntimeException t = new RuntimeException("This is new Exception...");
      t.initCause(new Throwable("ABCD"));
      throw t;
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

java.lang.Throwable: ABCD

示例:獲取 Exception 的初始原因

以下示例演示了 java.lang.Throwable.getCause() 方法的使用。在此程式中,我們定義了一個名為 raiseException() 的方法,在其中定義了一個 Exception,並使用 initCause() 方法將其初始原因設定為帶有訊息“ABCD”的可丟擲物件。在 main 方法中,呼叫了 raiseException() 方法。在 catch 塊中,我們處理異常並使用 getCause() 方法列印其原因。

package com.tutorialspoint;

public class ThrowableDemo {

   public static void main(String[] args) throws Throwable {
     try {
         raiseException();
      } catch(Exception e) {
         System.out.println(e.getCause());
      }
   }
  
   public static void raiseException() throws Exception {

      Exception t = new Exception("This is new Exception...");
      t.initCause(new Throwable("ABCD"));
      throw t;
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

java.lang.Throwable: ABCD
java_lang_throwable.htm
廣告