springmvc学习笔记(29)——HandleException处理异常

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

                       

如何使用HandleException

在程序中,异常是最常见的,我们需要捕捉异常并处理它,才能保证程序不被终止。

最常见的异常处理方法就是用try   catch来捕捉异常。这次我们使用springmvc给我们提供的方法来处理异常

先模拟一个异常出现的场景。以下是一个简单的数学异常

    @RequestMapping("testExceptionHandle")    public String testExceptionHandle(@RequestParam("i")Integer i){        System.out.println(10/i);        return "hello";    }
   
   
  • 1
  • 2
  • 3
  • 4
  • 5

当i的值为0的时候,就会抛出数学异常。该如何捕捉呢,我们使用ExceptionHandler注解

    //注意,该注解不是加在产生异常的方法上,而是另外写一个方法    @ExceptionHandler({ArithmeticException.class})    public String testArithmeticException(Exception e){        System.out.println("ArithmeticException:"+e);        return "error";    }
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
 
     
  • ExceptionHandler 的value属性是一个Class 数组,因此我们可以在该注解的属性中加入多个异常类
  •  
  • 当目标方法产生异常时,将被这个方法捕捉,我们可以得到异常的实例
  •  
  • 注意,捕捉异常的方法要和目标方法在同一个controller中
  •  

HandleException的优先级

当一个controller中有多个HandleException注解出现时,那么异常被哪个方法捕捉呢?这就存在一个优先级的问题

    @ExceptionHandler({ArithmeticException.class})    public String testArithmeticException(Exception e){        System.out.println("ArithmeticException:"+e);        return "error";    }    @ExceptionHandler({RuntimeException.class})    public String testRuntimeException(Exception e){        System.out.println("RuntimeException"+e);        return "error";    }    @RequestMapping("testExceptionHandle")    public String testExceptionHandle(@RequestParam("i")Integer i){        System.out.println(10/i);        return "hello";    }
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
 

如以上代码所示,目标方法是testExceptionHandle,另外两个方法被ExceptionHandler注解修饰。

访问目标方法,让它抛异常,看控制台打印结果,发现它抛了ArithmeticException:java.lang.ArithmeticException: / by zero这个异常

因此我们可以确定,ExceptionHandler的优先级是:在异常的体系结构中,哪个异常与目标方法抛出的异常血缘关系越紧密,就会被哪个捕捉到。

捕捉全局的异常

ExceptionHandler只能捕捉同一个controller中的异常,其实我们也有办法捕捉整个程序中所有的异常

新建一个类,加上@ControllerAdvice注解

package com.zj.controller;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;//处理异常@ControllerAdvicepublic class HandleForException {    @ExceptionHandler({ArithmeticException.class})    public String testArithmeticException(Exception e){        System.out.println("ArithmeticException:"+e);        return "error";    }}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

在这个类中使用ExceptionHandler,就能捕捉所有的controller中发生的异常

           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_43678306/article/details/84104624