方法套用try catch以及e.getCause().getMesage()与e.getMessage()使用异常的处理
在项目中难免会遇到多个方法套用try catch的情况。今天主要针对该情况,用一个简单的小demo来区别该情况。
1.方法都使用e.printStackTrace()来输出错误堆栈信息。会在最先的catch到异常并且抛出,套在外面的try catch不会catch异常。
demo:
public class DemoController {
private static final Logger LOGGER = LoggerFactory.getLogger(DemoController.class);
@RequestMapping(value = "/test", method = RequestMethod.GET)
public void say() {
int i = 0;
try{
LOGGER.info("START");
div(i);
}catch(Exception e){
e.printStackTrace();
}
}
private double div(int i){
double num = 0;
try{
LOGGER.info("start div");
num = i/0;
}catch(Exception e){
e.printStackTrace();
}
return num;
}
}
异常情况:
2.里面方法用e.getCause().getMesage(),会在执行e.getCause().getMesage()抛出异常到外面的try catch中执行e.printStackTrace信息。
demo:
demo:
public class DemoController {
private static final Logger LOGGER = LoggerFactory.getLogger(DemoController.class);
@RequestMapping(value = "/test", method = RequestMethod.GET)
public void say() {
int i = 0;
try{
LOGGER.info("START");
div(i);
}catch(Exception e){
e.printStackTrace();
}
}
private double div(int i){
double num = 0;
try{
LOGGER.info("start div");
num = i/0;
}catch(Exception e){
LOGGER.error("ERROR:{}",e.getCause().getMesage());
LOGGER.error("ERROR occurred.");
}
return num;
}
}
异常情况:
3.里面方法用e.getMesage(),方法会继续往下执行,外面的try catch也不会捕捉异常。
demo:
public class DemoController {
private static final Logger LOGGER = LoggerFactory.getLogger(DemoController.class);
@RequestMapping(value = "/test", method = RequestMethod.GET)
public void say() {
int i = 0;
try{
LOGGER.info("START");
div(i);
}catch(Exception e){
e.printStackTrace();
}
}
private double div(int i){
double num = 0;
try{
LOGGER.info("start div");
num = i/0;
}catch(Exception e){
LOGGER.error("ERROR:{}",e.getMesage());
LOGGER.error("ERROR occurred.");
}
return num;
}
}
异常情况:
总结:
情况1:内外都是e.printStackTrace(),里面的方法catch 异常不会再到外面catch捕捉到;
情况2:里面方法用e.getCause().getMesage(),里面的异常会抛出到外面的catch块中去处理;
情况3: 里面方法用e.getMesage(),里面的方法在catch块中继续执行,也不会再被外面的catch捕捉。