English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Contrôle de flux Java

Java tableau

Java orienté objet (I)

Java orienté objet (II)

Java orienté objet (III)

Java Exception Handling

Java Liste (List)

Java Queue (file d'attente)

Java Map

Java Set

Java entrée/sortie (I/O)

Lecteur Java/Writer

Autres sujets Java

Programme Java convertissant le suivi de pile en chaîne

Java complete list of examples

Dans ce programme, vous apprendrez à convertir le suivi de pile en chaîne en Java.

Exemple : convertir le suivi de pile en chaîne

import java.io.PrintWriter;
import java.io.StringWriter;
public class PrintStackTrace {
    public static void main(String[] args) {
        try {
            int division = 0 / 0;
        } catch (ArithmeticException e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String exceptionAsString = sw.toString();
            System.out.println(exceptionAsString);
        }
    }
}

When you run the program, the output will be similar to the following content:

java.lang.ArithmeticException: / by zero
    at PrintStackTrace.main(PrintStackTrace.java:9)

In the above program, we force the program to throw an ArithmeticException by dividing 0 by 0

In the catch block, we use StringWriter and PrintWriter to print any given output as a string. Then we use the exception's printStackTrace() method to print the stack trace and write it to the writer

Then, we just need to use the toString() method to convert it to a string.

Java complete list of examples