
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Differences Between printStackTrace() and getMessage() Methods in Java
There are two ways to find the details of the exception, one is the printStackTrace() method and another is the getMessage() method.
printStackTrace() method
This is the method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error class and java.lang.Exception class.
This method will display the name of the exception and nature of the message and line number where an exception has occurred.
Example
public class PrintStackTraceMethod { public static void main(String[] args) { try { int a[]= new int[5]; a[5]=20; } catch (Exception e) { e.printStackTrace(); } } }
Output
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 at PrintStackTraceMethod.main(PrintStackTraceMethod.java:5)
getMessage() method
This is a method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error and java.lang.Exception classes.
This method will display the only exception message.
Example
public class GetMessageMethod { public static void main(String[] args) { try { int x=1/0; } catch (Exception e) { System.out.println(e.getMessage()); } } }
Output
/ by zero
Advertisements