Friday, 13 April 2018

Stack trace to String Example

  1. /*
            Java Stacktrace to String Example
            This Java Stacktrace to String example shows how to get Stacktrace of any exception
            to String.

    public class StackTraceToStringExample {

            public static void main(String args[]){


                            //this will throw NumberFormatException
                            Integer.parseInt(“Not a number”);

                    }catch(NumberFormatException e){

                             * To convert Stacktrace to String in Java, use
                             * printStackTrace(PrintWrite pw) method of Throwable
                             * class.
                            //create new StringWriter object
                            StringWriter sWriter = new StringWriter();

                            //create PrintWriter for StringWriter
                            PrintWriter pWriter = new PrintWriter(sWriter);

                            //now print the stacktrace to PrintWriter we just created

                            //use toString method to get stacktrace to String from StringWriter object
                            String strStackTrace = sWriter.toString();

                            System.out.println(“Stacktrace converted to String: “ + strStackTrace);


    Output of above given Java Stacktrace to String would be
    Stacktrace converted to String: java.lang.NumberFormatException: For input string: “Not a number”
            at java.lang.NumberFormatException.forInputString(Unknown Source)
            at java.lang.Integer.parseInt(Unknown Source)
            at java.lang.Integer.parseInt(Unknown Source)
            at StackTraceToStringExample.main(

1 comment:

Popular Posts


Android (21) AngularJS (1) Books (3) C (75) C++ (81) Data Strucures (4) Engineering (13) FPL (17) HTML&CSS (38) IS (25) Java (85) PHP (20) Python (94) R (69) Selenium Webdriver (2) Software (13) SQL (27)