Java Program to convert a stack trace to a string using StringWriter and PrintWriter:

               Whenever a program is written, it should be compiled and executed. Both of this process makes use of memory. During the time of execution, stack trace is generated. Stack trace is useful for debugging purpose.

  • ·       Let us create a java program to display stack trace.  It uses dumpStack() built in function.
  • ·       First, create a class Main1 and include the function calls demo(),demo1(),demo2() ,demo3() and demo4().
  • ·       Add the built in function call Thread.dumpStack() in demo4() .

public class Main1 {

  public static void main(String args[]) {

    demo();

  }

  static void demo() {

    demo1();

  }

  static void demo1() {

    demo2();

  }

  static void demo2() {

    demo3();

  }

  static void demo3() {

   demo4();

  }

  static void demo4()

  {

 Thread.dumpStack(); }

}

  • ·       Save this file as “Main1.java”. Compile and execute this file in command prompt.
  • ·       This will give you the output.

 Java program to convert a stack trace to a string using StringWriter and PrintWriter:

  • Import two built in packages java.io.Printwriter and java.io.StringWriter.

import java.io.PrintWriter;

import java.io.StringWriter;

//Create a class Main2 ans save it as “Main2.java”

public class Main2 {

    public static void main(String[] args) {

        try {

            //Here, a sample of exception (divide by zero) is created

            int a = 10 / 0;

        } catch (Exception e) {

            // A process of Converting a stack trace to a string

           // Create  objects for StringWriter and PrintWriter. Use the builtin function                       

            //  printStackTrace()

            StringWriter sw = new StringWriter();

            PrintWriter pw = new PrintWriter(sw);

            e.printStackTrace(pw);

            String stackTrace = sw.toString();

            // Display the stack trace as a string

            System.out.println("Stack Trace as a String:");

            System.out.println(stackTrace);

        }

    }

}

  • Compile and execute this program. This shows the output.
These are all ways to use stack trace.

No comments:

Post a Comment