java异常分类:
1.error
2exception
两种都是Throwable的子类
error 无法处理的异常 比如(oom)
exception :可以处理的异常
1.运行异常(发生在程序运行时间,比如算数异常)
2.系统异常 (发生在编译时间,比如代码语法不对)
异常图
常见的运行异常
1、NullpointException
2.ClassNotFoundException
3.ClassCastException
4.ArithmeticException
常见的收件异常
1.IOException
2.FileNotFoundException
3.SQLException
spring 常用的异常
[email protected]
2ControllerAdvice
3.实现ExceptionHanlerResolver接口
@ExceptionHandler
1 package controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.ExceptionHandler; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 7 import exception.MyException; 8 //只能在一个类中使用 9 @Controller 10 public class BaseController { 11 12 @ExceptionHandler //跳转到异常页面 13 public String exception(MyException ex){ 14 System.out.println(ex.getMessage()); 15 ex.printStackTrace(); 16 return "exception"; 17 } 18 19 @RequestMapping("/test") 20 public void test(){ 21 throw new MyException("出错了"); 22 } 23 public static void main(String[] args) { 24 BaseController s=new BaseController(); 25 s.test(); 26 } 27 }
实现ExceptionHanlerRolver接口(可以进行全局配置)
package controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; @Component public class HandlerExceptionRolver implements HandlerExceptionResolver{ @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex) { System.out.println("This is exception "+ex); ModelAndView view=new ModelAndView("exception"); return view; } }
ControllerAdvice
时间: 2024-12-27 00:36:15