获得java.lang.Throwable错误堆栈信息

在java语言中java.lang.Throwable是所有error、exception的父类。异常体系对于问题的查找、编码的实现都是非常有帮助的。

当你catch到一个异常Throwable e后,大家最常用的做法就是

e.printStackTrace();

如果你使用了log4j,那么我建议使用

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
class Axxx {
	protected final Log logger = LogFactory.getLog(getClass());
	{
		Throwable e;
		// .......
		// .......
		logger.error(e);
	}
}

如果你要将错误堆栈的系想你存储到数据库中,可以参考下面的类

package com.mahh.jdk;

import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author mahh
 *
 * @since:2013-1-28 上午10:06:40
 *
 */
public class ThrowableInformation {
	protected final Log logger = LogFactory.getLog(getClass());
	/**=======================================================================
	 * 获得操作系统中,换行字符串。如Micorsoft Windows XP专业版中换行符"\r\n"
	 * =======================================================================
	 */
	// Note that the line.separator property can be looked up even by applets.
	// 参考org.apache.log4j.Layout
	public final static String LINE_SEP = System.getProperty("line.separator");
	// 参考java.io.BufferedWriter
	public final static String LINE_SEP2 = (String) java.security.AccessController
			.doPrivileged(new sun.security.action.GetPropertyAction(
					"line.separator"));

	/**
	 * @Description:将Throwable对象的错误堆栈内容形成字符串
参考 * {@link org.apache.log4j.spi.ThrowableInformation} * 代码 * @param throwable * 异常对象 * @return * @author mahh * @since:2014-9-30 下午02:32:51 */ public static String[] getThrowableStrRep(Throwable throwable) { if (throwable == null) { return new String[0]; } StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); throwable.printStackTrace(pw); pw.flush(); LineNumberReader reader = new LineNumberReader(new StringReader( sw.toString())); ArrayList lines = new ArrayList(); try { String line = reader.readLine(); while (line != null) { lines.add(line); line = reader.readLine(); } } catch (IOException ex) { lines.add(ex.toString()); } String[] rep = new String[lines.size()]; lines.toArray(rep); return rep; } // 测试代码 public static void main(String[] args) { RuntimeException e1 = new RuntimeException("aaa"); RuntimeException e2 = new RuntimeException("e2", e1); RuntimeException e3 = new RuntimeException(e2); String[] errorStrArray = getThrowableStrRep(e3); for (int i = 0; i < errorStrArray.length; i++) { System.out.println(errorStrArray[i]); } } }

最后,提一下debugg调试的时候,会遇到的一个奇怪的现象,java.lang.Throwable实例在调试时显示

你可能感兴趣的:(Java)