- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Place Stack Trace into a String in Java
In order to place stack trace into a String in Java, we use the java.io.StringWriter and java.io.PrintWriter classes. In a catch block, after catching the exception, we print the stack trace by printStackTrace() method and write it into the writer and then use the ToString() method to convert it into a String.
Let us see a program to place the stack trace into a String in Java.
Example
import java.io.PrintWriter; import java.io.StringWriter; public class Example { public static void main(String[] args) { try{ int ans = 10/0; }catch (ArithmeticException ex) { StringWriter s= new StringWriter(); ex.printStackTrace(new PrintWriter(s)); // writing the stack trace in the writer String str = s.toString(); // converting it into a String System.out.println(str); } } }
Output
java.lang.ArithmeticException: / by zero at Example.main(Example.java:8)
- Related Articles
- Java Program to Convert a Stack Trace to a String
- Print stack trace in Java
- How to get stack trace using thread in Java 9?
- How can I get a stack trace for a JavaScript exception?
- How to rethrow InnerException without losing stack trace in C#?
- Insert a String into another String in Java
- How can I get a JavaScript stack trace when I throw an exception?
- Java Program to Insert a string into another string
- Stack in Java
- Convert Short into String in Java
- How to convert a String into int in Java?
- Stack in Java Programming
- Not able to push all elements of a stack into another stack using for loop in JavaScript?
- Implement a stack from a LinkedList in Java
- Java Program to Convert a String into the InputStream

Advertisements