java 中的异常:
运行时异常:(如:空指针异常,数组越界,数字转换异常,运算异常,非法参数异常)程序可以编写代码处理,也可以不处理。
非运行时异常: (如:io异常,sql 异常)程序必须要编写代码处理(强制处理),(try{}catch{} 或者 throws)
error : 系统异常,出现这种异常一般都凉凉了。
示例一:运行时异常可以不用处理
public class BaseException extends RuntimeException {
private String code;
private String msg;
public BaseException(String code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
}
自定义一个异常继承RuntimeException 然后直接抛出异常。
public class Test {
public static void getLaLa () {
throw new BaseException("201", "lalala");
}
public static void main(String[] args) {
getLaLa();
}
}
在系统中,我们可以这样做:先声明一个自定义异常
public class IllegalArgumentException extends RuntimeException{
public String code;
public String message;
public IllegalArgumentException(ResultEnum resultEnum) {
super(resultEnum.message);
this.code = resultEnum.code;
this.message = resultEnum.message;
}
public IllegalArgumentException(String code ,String errorMessage) {
super(errorMessage);
this.code = code;
this.message = errorMessage;
}
}
然后我们写一个异常捕获类,来捕获这个异常,然后抛给前台:
@RestControllerAdvice
@Slf4j
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler extends BaseExceptionHandler {
@ExceptionHandler(value = BaseException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public IntegralResponse notDecryptException(BaseException e){
log.error("系统内部异常,异常信息", e);
return new IntegralResponse().code(e.getCode().toString()).message(e.getMessage());
}
@ExceptionHandler(value = IllegalArgumentException.class)
// @ResponseStatus(HttpStatus.UNAUTHORIZED)
public IntegralResponse illegalArgumentException(IllegalArgumentException e){
log.error("参数异常,异常信息", e);
return new IntegralResponse().code(e.code).message(e.getMessage());
}
}
但是如果继承的是exception的话
public class BaseException extends Exception {
private String code;
private String msg;
public BaseException(String code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
}
如果不抛出异常的话就会编译出错。
public class Test {
public static void getLaLa () throws BaseException {
throw new BaseException("201", "lalala");
}
public static void main(String[] args) {
try {
getLaLa();
} catch (BaseException e) {
e.printStackTrace();
}
}
}
最后问请教一个问题
public class BaseException1 extends RuntimeException {
public String code;
public String msg;
public BaseException1(String code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
}
public class Test {
public static void exception2 () throws BaseException1{
throw new BaseException1("201", "lalala");
}
public static void main(String[] args) {
try {
exception2();
} catch (BaseException1 e) {
System.err.println(e.code);
System.err.println(e.msg);
}
}
}
继承exception 后,声明了两个成员变量,没有写get和set方法,但是在 main 函数中 BaseException1 的实例 e
为啥可以直接点出来code,和 msg?