public class ExceptionTrans {
/**
* 异常信息转换为字符串
*
* @param t 异常对象
* @return
*/
public static String ex2String(Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw, true));
return sw.getBuffer().toString();
}
public static void main(String[] args) {
String ex = null;
try {
int a = 0;
a = a / a;
if (true) {
throw new CordException("test");
}
} catch (Exception e) {
e.printStackTrace();
ex = ex2String(e);
System.out.println("------------------------");
}
System.out.printf(ex);
}
}
还可以使用ASIC控制码输出不同的字体颜色
package com.example.demopromclient;
public class Test {
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_CYAN = "\u001B[36m";
public static void main(String[] args) {
System.out.println(ANSI_RED + "this text is red" + ANSI_RESET);
System.out.println(ANSI_YELLOW + "this text is yellow" + ANSI_RESET);
System.out.println(ANSI_CYAN + "this text is cyan" + ANSI_RESET);
}
}