
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
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)
Advertisements