springmvc学习笔记(29)——@ExceptionHandle 注解

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";
    }


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

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

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

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

package com.zj.controller;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

//处理异常
@ControllerAdvice
public class HandleForException {

    @ExceptionHandler({ArithmeticException.class})
    public String testArithmeticException(Exception e){
        System.out.println("ArithmeticException:"+e);
        return "error";
    }
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值