beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – StackTrace to String conversion

By Chaitanya Singh | Filed Under: Java Conversion

There are times when we want to convert the occurred exception to String. In the following program we are converting the stacktrace to String by using Throwable.printStackTrace(PrintWriter pw).

Example: Converting Exception StackTrace to String

package com.beginnersbook.string;
import java.io.PrintWriter;
import java.io.StringWriter;

public class StacktraceToString {
    public static void main(String args[]){
        try{
            int i =5/0;
            System.out.println(i);
        }catch(ArithmeticException e){
            /* This block of code would convert the
             * stacktrace to string by using
             * Throwable.printStackTrace(PrintWriter pw)
             * which sends the stacktrace to the writer
             * that we can convert to string using tostring()
             */
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            String stacktraceString = sw.toString();
            System.out.println("String is: "+stacktraceString);
        }
    }
}

Output:

String is: java.lang.ArithmeticException: / by zero
at com.beginnersbook.string.StacktraceToString.main(StacktraceToString.java:8)
❮ PreviousNext ❯

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Conversion

  • Java String to int
  • Java int to String
  • Java String to long
  • Java long to String
  • Java String to double
  • Java double to String
  • Java double to int
  • Java int to double
  • Java int to long
  • Java long to int
  • Java char to String
  • Java char to int
  • Java int to char
  • Java float to String
  • Java boolean to String
  • Java String to boolean
  • Java binary to decimal
  • Java decimal to binary
  • Java binary to Octal
  • Java decimal to hexadecimal
  • Java Hex to decimal
  • Java decimal to Octal
  • Java Octal to decimal
  • Java ASCII to String
  • Java Writer to String
  • Java StackTrace to String
  • Java String to ArrayList
  • Java StringBuffer to String
  • Java InputStream to String

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap