![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Importance of the getCause() method in Java?\n
The getCause() method is from Throwable class and we can use this method which returns the cause of the exception or returns null if the cause of the exception is not known. The getCause() method doesn’t accept any arguments and doesn’t throw an exception. It returns the cause that was provided by one of its constructors or that was determined by the formation of the initCause() method of Throwable class.
Syntax
public Throwable getCause()
Example
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() } } }
Output
Cause = java.lang.ArrayIndexOutOfBoundsException: 8
Advertisements