自定义异常类
如何自定义异常类?
- 继承于现有的异常结构;RuntimeException 、Exception
- 提供全局常量:serialVersionUID
- 提供重载的构造器
案例:
public class MyException extends Exception{
static final long serialVersionUID = -7034897193246939L;
public MyException(){
}
public MyException(String msg){
super(msg);
}
}
public class StudentTest {
public static void main(String[] args) {
try {
Student s = new Student();
s.regist(-1001);
System.out.println(s);
} catch (Exception e) {
// e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
class Student{
private int id;
public void regist(int id) throws Exception {
if(id > 0){
this.id = id;
}else{
throw new MyException("不能输入负数");
}
}
@Override
public String toString() {
return "Student [id=" + id + "]";
}
}
全局异常处理机制
1 需求分析
说明: 通过try-catch 方式可以捕获异常.但是如果代码中有大量的数据需要通过try-catch的方式进行操作,会导致代码的结构混乱. 最好的方式可以采用全局异常处理的方式完成.
2 定义全局异常处理机制
package com.jt.aop;
import com.jt.vo.SysResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//spring中的通知 核心原理:Spring AOP机制
@RestControllerAdvice //只对Controller代码层级有效.
public class SysResultException {
//当程序发生异常时, 如果没有try-catch则直接向上抛出异常.
//该注解只拦截运行时异常.
@ExceptionHandler({RuntimeException.class})
public SysResult exception(Exception e){
e.printStackTrace();
return SysResult.fail();
}
}
注意;
@RestControllerAdvice 只对Controller代码层级有效.
@ExceptionHandler 该注解只拦截运行时异常