- Trending Categories
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
Java Program to Convert a Stack Trace to a String
The Java.io.StringWriter class is a character stream that collects its output in a string buffer, which can then be used to construct a string. Closing a StringWriter has no effect.
The Java.io.PrintWriter class prints formatted representations of objects to a text-output stream.
Using these two classes you can convert a Stack Trace to a String.
Example
import java.io.PrintWriter; import java.io.StringWriter; public class StackTraceToString { public static void main(String args[]) { try { int a[] = new int[2]; System.out.println("Access element three :" + a[3]); } catch (ArrayIndexOutOfBoundsException e) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); String myString = writer.toString(); System.out.println("Stack trace message ::"+myString); } } }
Output
Stack trace message ::java.lang.ArrayIndexOutOfBoundsException: 3 at lastRound.StackTraceToString.main(StackTraceToString.java:10)
Advertisements