堆栈信息打印

堆栈信息的打印,有助于我们定位问题的所在,不仅仅是定位到错误的当前行,

我们最常见到的堆栈信息是在异常处理时,try...catch中打印异常信息:e.printStackTrace();

下面为常用的四中打印堆栈信息的方法:

1、通过Throwable对象的getStackTace()方法

	public static void printCallStackTrace1() {
		Throwable ex = new Throwable();
		StackTraceElement[] stackElements = ex.getStackTrace();
		if (stackElements != null) {
			for (int i = 0; i < stackElements.length; i++) {
				System.out.print("className = " + stackElements[i].getClassName() + "\n");
				System.out.print("FileName = " + stackElements[i].getFileName() + "\n");
				System.out.print("LineNumber = " + stackElements[i].getLineNumber() + "\n");
				System.out.println("MethodName = " + stackElements[i].getMethodName() + "\n");
				System.out.println("-----------------------------------");
			}
		}
	}
打印结果:

className = com.liuyunlong.java.poi.Test
FileName = Test.java
LineNumber = 44
MethodName = printCallStackTrace1

-----------------------------------
className = com.liuyunlong.java.poi.Test
FileName = Test.java
LineNumber = 13
MethodName = main

-----------------------------------

2、通过Exception对象的printStackTrace()方法

	public static void printCallStackTrace2() {
		Exception e = new Exception("this is a log");
		e.printStackTrace();
	}

打印结果:

java.lang.Exception: this is a log
	at com.liuyunlong.java.poi.Test.printCallStackTrace2(Test.java:39)
	at com.liuyunlong.java.poi.Test.main(Test.java:14)

3、通过当前线程对象的getStackTrace()方法

	private static void printCallStackTrace3() {
		StackTraceElement[] traceElements = Thread.currentThread().getStackTrace();
		if (traceElements != null) {
			for (int i = 0; i < traceElements.length; i++) {
				System.out.print("className = " + traceElements[i].getClassName() + "\n");
				System.out.print("FileName = " + traceElements[i].getFileName() + "\n");
				System.out.print("LineNumber = " + traceElements[i].getLineNumber() + "\n");
				System.out.println("MethodName = " + traceElements[i].getMethodName() + "\n");
				System.out.println("-----------------------------------");
			}
		}
	}

打印结果:

className = java.lang.Thread
FileName = null
LineNumber = -1
MethodName = getStackTrace

-----------------------------------
className = com.liuyunlong.java.poi.Test
FileName = Test.java
LineNumber = 26
MethodName = printCallStackTrace3

-----------------------------------
className = com.liuyunlong.java.poi.Test
FileName = Test.java
LineNumber = 15
MethodName = main

-----------------------------------

4、org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e)

	private static void printCallStackTrace4() {
		Exception e = new Exception("this is a log");
		String fullStackTrace = org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e);
		System.out.println(fullStackTrace);
	}

打印结果为:

java.lang.Exception: this is a log
	at com.liuyunlong.java.poi.Test.printCallStackTrace4(Test.java:20)
	at com.liuyunlong.java.poi.Test.main(Test.java:16)



你可能感兴趣的:(堆栈信息打印)