1、异常概述
程序在编写运行过程中,难免会出现意料之外的错误,异常为程序退出提供了安全通道,提高程序的健壮性和容错性。
2、异常的结构
Throwable是所有异常的父类,分为异常Exception和错误Error。
Error是程序无法处理的错误,表示运行应用程序中较严重问题。大多数错误与代码编写者执行的操作无关,而表示代码运行时 JVM(Java 虚拟机)出现的问题,如OutOfMemoryError、StackOverflowError。
Exception是在程序层级发生的,并且可以由程序处理的异常,分为运行时异常(RuntimeException及其子类)和编译期异常(除了运行时异常的其他类)。
编译期异常是指程序可预见的错误,该类异常必须在程序编写时处理,否则无法编译通过,如IOException、ClassNotFoundException等。
运行时异常(RuntimeException)一般是由程序逻辑错误引起的异常,如NullPointerException、ArithmeticException等。
受检异常(Checked Exception)相当于编译期异常
非受检异常(Unchecked Exception)相当于RuntimeException和Error
3、异常处理机制
主要是try、catch、finally、throw、throws等关键字的使用,内容不多且属于基本知识,不作赘述。
4、自定义异常
1.首先定义异常类型枚举
package exception;
public enum ExceptionTypeEnum {
LOGIN_FAIL("401","登录失败"),
NO_SERVICE("404", "连接失败"),;
String errCode;
String errMsg;
ExceptionTypeEnum(String errCode, String errMsg) {
this.errCode = errCode;
this.errMsg = errMsg;
}
}
2.然后是自定义异常类,继承RuntimeException
package exception;
public class BizException extends RuntimeException {
private ExceptionTypeEnum exceptionType;
public BizException() {
super();
}
public BizException(String message) {
super(message);
}
public BizException(String message, Throwable cause) {
super(message, cause);
}
public BizException(Throwable cause) {
super(cause);
}
protected BizException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public BizException(ExceptionTypeEnum exceptionType) {
this(exceptionType.errMsg);
this.exceptionType = exceptionType;
}
@Override
public void printStackTrace(){
System.out.println(("异常代码: " + exceptionType.errCode + ", 异常信息: " + exceptionType.errMsg));
}
}
3.最后是测试类
package exception;
public class BizException extends RuntimeException {
private ExceptionTypeEnum exceptionType;
public BizException() {
super();
}
public BizException(String message) {
super(message);
}
public BizException(String message, Throwable cause) {
super(message, cause);
}
public BizException(Throwable cause) {
super(cause);
}
protected BizException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public BizException(ExceptionTypeEnum exceptionType) {
this(exceptionType.errMsg);
this.exceptionType = exceptionType;
}
@Override
public void printStackTrace(){
System.out.println(("异常代码: " + exceptionType.errCode + ", 异常信息: " + exceptionType.errMsg));
}
}
测试结果如下:
异常代码: 404, 异常信息: 连接失败