try()catch{}和全局异常的关系

try()catch{}和全局异常对于异常的处理的优先级:
结论:
    try()catch{}高于全局异常

验证:

创建一个springboot工程

定义一个全局异常类

@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalException {

    @ExceptionHandler(value = IllegalStateException.class)
    public JSONObject handlerIlle(IllegalStateException e){
        log.error("全局异常:{}",e.getMessage());
        JSONObject result = new JSONObject();
        result.put("code","1");
        result.put("msg",e.getMessage());
        return result;
    }
    @ExceptionHandler(value = NullPointerException.class)
    public JSONObject handlerIlle(NullPointerException e){
        log.error("全局异常:{}",e.getMessage());
        JSONObject result = new JSONObject();
        result.put("code","2");
        result.put("msg",e.getMessage());
        return result;
    }
    @ExceptionHandler(value = ArithmeticException.class)
    public JSONObject handlerIlle(ArithmeticException e){
        log.error("全局异常:{}",e.getMessage());
        JSONObject result = new JSONObject();
        result.put("code","3");
        result.put("msg",e.getMessage());
        return result;
    }

}

测试代码

@RestController
@RequestMapping("lombok")
@Slf4j
public class LombokController {

    /**
     * 调用的方法抛出了异常,如果有try()catch{},那么就会try()catch{},而不会被全局异常捕获
     * @return
     */
    @RequestMapping("useTry")
    public JSONObject useTry(){
        JSONObject data = null;
        try {
            data = getData();
        } catch (Exception e) {
            log.error("捕获到异常::",e.getMessage());
        }

        return  data;
    }
    @RequestMapping("noTry")
    public JSONObject noTry(){
        JSONObject data = null;
        data = getData();

        return  data;
    }

    public JSONObject getData() {
        if(1==1){
            throw new NullPointerException("我抛出异常了");
        }
        return null;
    }
}

启动服务

1.请求/lombok/userTry
控制台输出如下,可以看到是走的try()catch{},而不会被全局异常捕获

捕获到异常::java.lang.NullPointerException: 我抛出异常了

2.请求/lombok/noTry
控制台输出如下,可以看到是被全局异常捕获

GlobalException  : 全局异常:我抛出异常了

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值