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 常用的异常
1.@ExceptionHandler
2.实现ExceptionHanlerResolver接口
3.通过spring提供的SimpleMappingException
@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; } }
Spring 提供给我们的SimpleMappingExceptionRolver 异常类
1.可以设置默认发生异常跳转页面(defaultErrorView)
2.可以设置发生异常改变默认http新号码(defaultStateCode)
3.可以设置发生特定异常类所跳转的页面(exceptionMappings)
java中异常的捕获
try{
//要捕获的异常
}
catch( exception e){
//异常处理
}finally{
//最终一定要执行的代码
}