一、前言
基于c3p0包中com.mchange.lang.ThrowableUtils异常工具类对异常轨迹信息转换为字符串信息、check检查判断异常类型是Exception或者RuntimeException等。
二、源码示例
方法一
package com.mchange.lang;@b@@b@import java.io.PrintWriter;@b@import java.io.StringWriter;@b@@b@public final class ThrowableUtils@b@{@b@ public static String extractStackTrace(Throwable t)@b@ {@b@ StringWriter me = new StringWriter();@b@ PrintWriter pw = new PrintWriter(me);@b@ t.printStackTrace(pw);@b@ pw.flush();@b@ return me.toString();@b@ }@b@@b@ public static boolean isChecked(Throwable t)@b@ {@b@ return ((t instanceof Exception) && (!(t instanceof RuntimeException)));@b@ }@b@@b@ public static boolean isUnchecked(Throwable t)@b@ {@b@ return (!(isChecked(t)));@b@ }@b@}
方法二
import java.io.ByteArrayOutputStream;@b@@b@ public final class ThrowableUtils@b@{@b@ /**@b@ * 将异常信息转化成字符串@b@ * @param t@b@ * @return@b@ * @throws IOException@b@ */@b@ public static String exception(Throwable t) throws IOException {@b@ if(t == null){@b@ return null;@b@ }@b@ ByteArrayOutputStream baos = new ByteArrayOutputStream();@b@ try{@b@ t.printStackTrace(new PrintStream(baos));@b@ }finally{@b@ baos.close();@b@ }@b@ return baos.toString();@b@ }@b@@b@@b@@b@}
方法三
import java.io.IOException;@b@import java.io.PrintWriter;@b@import java.io.StringWriter;@b@@b@public final class ThrowableUtils@b@{ /**@b@ * 将异常信息转化为字符串@b@ *@b@ * @param throwable 异常对象@b@ * @return 异常信息字符串 */@b@ public static String throwableToString(Throwable throwable) { try (StringWriter stringWriter = new StringWriter();@b@ PrintWriter writer = new PrintWriter(stringWriter)) {@b@ throwable.printStackTrace(writer);@b@ StringBuffer buffer = stringWriter.getBuffer(); return buffer.toString();@b@ } catch (IOException e) { throw new RuntimeException(e);@b@ }@b@ }@b@}