首先来看异常的根节点
Throwable是所有异常的根,java.lang.Throwable
Error是错误,java.lang.Error
Error类体系描述了Java运行系统中的内部错误以及资源耗尽的情形.这种异常会导致JVM中断,必须人为处理
java虚拟机中发生的,不需要程序猿try-catch或者抛出
StackOutFlowError(栈溢出)和OutOfMemoryError(堆溢出),都属于Error,中间层是VirtualMachineError
Exception是异常,java.lang.Exception 继承 Throwable
IOException(必须捕获异常)
FileNotFoundException
EOFException
RuntimeException(可捕获异常)
NullPointerException
ClassNotFoundException
...
自定异常
public class TraceException extends RuntimeException{ private ExceptionEnums exceptionEnums; public TraceException(ExceptionEnums exceptionEnums) { super(exceptionEnums.getMessage()); this.exceptionEnums = exceptionEnums; } public static String getTraceInfo(Throwable t) { StringWriter stringWriter= new StringWriter(); PrintWriter writer= new PrintWriter(stringWriter); t.printStackTrace(writer); StringBuffer buffer= stringWriter.getBuffer(); String[] str = buffer.toString().split("\r\n\t"); buffer = new StringBuffer(); buffer.append("exception:").append(str[0]).append(" detail:").append(str[1]); writer.close(); return buffer.toString(); } }
自定义返回信息
public enum ExceptionEnums { COMMON_EXP("5000", "系统异常"), NOT_FOUND_DATA_EXP("1001", "未找到数据") ; private String code; private String message; ExceptionEnums(String code, String message) { this.code = code; this.message = message; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
运行查看
public class ClientExcetion { public static void main(String[] args) { try { getData(); }catch (TraceException e){ System.out.println(e.getMessage()); } } public static void getData() { try { String[] a = {}; String c = a[3]; System.out.println(c); }catch (Exception e){ System.out.println(TraceException.getTraceInfo(e)); throw new TraceException(ExceptionEnums.COMMON_EXP); } } }