Java 輸出 printStackTrace 堆棧信息:
- import java.io.PrintWriter;
- import java.io.StringWriter;
-
- public class MainDemo {
- private static String USER_NAME;
-
- public static void main(String[] args) {
- try {
- // 空指針異常
- System.out.println(USER_NAME.equals(""));
- } catch (Exception ex) {
- ex.printStackTrace();
-
- System.out.println("----------------------------");
-
- Exception exception = ex;
- StringWriter writer = new StringWriter();
- exception.printStackTrace(new PrintWriter(writer));
- System.out.println(writer.getBuffer().toString());
- }
- }
- }
輸出結果:
- java.lang.NullPointerException
- at MainDemo.main(MainDemo.java:9)
- ----------------------------
- java.lang.NullPointerException
- at MainDemo.main(MainDemo.java:9)