被调用者抛出异常
1.没有try…catch…抛出异常的情况
void beanLoads() {
List<Object> ls = new ArrayList();
if (ls.size() == 0 || ls == null) {
throw new NullPointerException();
}
}
@Test
void test() {
try {
beanLoads();
} catch (NullPointerException e) {
System.out.print("没有try...catch的情况下捕获到空指针异常");
}
}
输出:
没有try...catch的情况下捕获到空指针异常
2.在有try…catch的情况下抛出异常
void beanLoads() {
List<Object> ls = new ArrayList();
try {
if (ls.size() == 0 || ls == null) {
throw new NullPointerException();
}
}catch (Exception e){
System.out.println("有try...catch的情况下捕获异常");
}
}
@Test
void test() {
try {
beanLoads();
} catch (NullPointerException e) {
System.out.println("捕获到空指针异常");
}
}
输出:有try...catch的情况下捕获异常
3.在循环体中,如果抛出异常将会终止循环
@Test
void beanLoads() throws Exception {
List<Object> ls = new ArrayList();
for(int i=0;i<20;i++){
if(i==5){
throw new Exception();
}
System.out.println(i);
}
}
输出01234
4.在spring事物处理中,如果希望抛出异常事物回滚,则不应该使用try…catch捕获异常,而是将异常抛出
@Override
@Transactional(rollbackFor = Exception.class)
public Map<String, String> importReportSettingOk(CommonsMultipartFile file) throws Exception
//异常抛出
if (custTaskVos.size() == 0 || custTaskVos == null) {
Map<String, String> results = new HashMap<>();
log.error("import task error, error task info: {}", JSON.toJSONString(taskExcelVo));
String errorStr = "第" + (count + 2) + "行任务编号不存在!" ;
throw new NullPointerException(errorStr);
}
注意,这里是不建议直接抛出空指针异常的,可以选择抛出自定义异常,这里为了简便直接抛出了空指针