- 创建SpringBoot工程,导入依赖
org.springframework.boot spring-boot-starter-web
- 编写异常类
//@ControllerAdvice //返回一个页面
@RestControllerAdvice //返回一个字符串或者JSON
public class MyException02 {
@ExceptionHandler(ArithmeticException.class)
public String arithmeticExceptionHandler(ArithmeticException e) {
return e.getMessage();
}
}
- 测试
@RestController
public class HelloController {
@GetMapping("/hello")
public void hello(){
int i=1/0;
}
}
成功!



