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 : 全局异常:我抛出异常了