getCause() method comes from Throwable class, we can use this method to return reason Exception or returns null (if the cause of the exception is unknown). getCause() The method does not accept any parameters and does not throw an exception. It returns the cause provided by one of its constructors or determined by the formation of the initCause() method of the Throwable class.
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); <strong>/</strong>/ throwing the exception to be caught by catch block in main() e.initCause(aiobe); // supplies the cause to getCause() } } }
Cause = java.lang.ArrayIndexOutOfBoundsException: 8
The above is the detailed content of What is the importance of getCause() method in Java?. For more information, please follow other related articles on the PHP Chinese website!