ExceptionEnum
/** 自定义异常枚举类 */ public enum ExceptionEnum { Exception404("页面没找到错误", 404), Exception500("后端错误", 500), Exception501("除数不能为0, 语法错误", 501) ; private String errorMsg; private Integer errorCode; ExceptionEnum(String errorMsg, Integer errorCode) { this.errorMsg = errorMsg; this.errorCode = errorCode; } public Integer getErrorCode() { return errorCode; } public String getErrorMsg() { return errorMsg; } }
MyException
/** 自定义异常类 */ public class MyException extends Exception { private String errorMsg; private Integer errorCode; public MyException() { } public MyException(String errorMsg, Integer errorCode) { this.errorMsg = errorMsg; this.errorCode = errorCode; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } public Integer getErrorCode() { return errorCode; } public void setErrorCode(Integer errorCode) { this.errorCode = errorCode; } }
Exception
// Throwable 子类: Exception // Exception 子类: RuntimeException public class ExceptionDemo public static void main(String[] args) { try { med2(); } catch (ArithmeticException e) { System.out.println(e.getMessage()); } try { med3(); } catch (ArithmeticException e) { System.out.println(e.getMessage()); } try { med4(); } catch (Exception e) { System.out.println("e.getMessage()=" + e.getMessage()); System.out.println(" e.getCause()=" + e.getCause()); StackTraceElement[] stackTrace = e.getStackTrace(); if (stackTrace == null || stackTrace.length == 0) { return; } Stream.of(stackTrace).forEach(ee -> System.out.println(" e.getStackTrace()=" + ee)); } // 自定义异常 try { med5(); } catch (MyException e) { System.out.println(e.getErrorCode() + "---" + e.getErrorMsg()); } } public static void med2() { throw new ArithmeticException("我自己抛出一个异常"); } public static void med3() { int i = 1 / 0; } public static void med4() throws Exception { try { int i = 1 / 0; } catch (ArithmeticException e) { throw new Exception("我自己抛出一个Exception异常信息", e); } } public static void med5() throws MyException { try { int i = 1 / 0; } catch (Exception e) { throw new MyException(ExceptionEnum.Exception501.getErrorMsg() , ExceptionEnum.Exception501.getErrorCode()); } } }