在android里面经常需要打印堆栈信息
1. 编写例子
public void ThrowException() {
// 调试打印堆栈而不退出
Log.d(TAG, Log.getStackTraceString(new Throwable()));
// 创建异常打印堆栈
Exception e = new Exception("this is a log");
e.printStackTrace();
// 获取当前线程的堆栈
for (StackTraceElement i : Thread.currentThread().getStackTrace()) {
Log.i(TAG, i.toString());
}
RuntimeException re = new RuntimeException();
re.fillInStackTrace();
Log.i(TAG, "stackTrace", re);
// 主动抛出异常调试
try {
Log.i(TAG,
"--------------------------------NullPointerException-----------1");
throw new NullPointerException();
} catch (NullPointerException e1) {
// TODO: handle exception
Log.i(TAG, "--------------------------------NullPointerException");
Log.e(TAG, Log.getStackTraceString(e1));
// e1.printStackTrace();
}
Log.i(TAG,
"--------------------------------NullPointerException-----------end");
}
1.1 getStackTraceString
使用 Log.d(TAG, Log.getStackTraceString(new Throwable()));方法打印堆栈如下:
2. printStackTrace
Exception e = new Exception("this is a log"); e.printStackTrace();
3. RuntimeException
RuntimeException re = new RuntimeException(); re.fillInStackTrace(); Log.i(TAG, "stackTrace", re);
5. 主动抛异常
// 主动抛出异常调试
try {
Log.i(TAG, "--------------------------------NullPointerException-----------1");
throw new NullPointerException();
} catch (NullPointerException e1) {
// TODO: handle exception Log.i(TAG, "--------------------------------NullPointerException");
Log.e(TAG, Log.getStackTraceString(e1));
// e1.printStackTrace(); }
Log.i(TAG, "--------------------------------NullPointerException-----------end");
虽然以上方法不尽一样,但打印出来的堆栈是一样的。\